﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Data.SqlClient;
using exel=Microsoft.Office.Interop.Excel; 

namespace Project_ScansiaPacific
{
    public partial class FrKhoThanhPham : DevComponents.DotNetBar.Office2007Form
    {
        public FrKhoThanhPham()
        {
            InitializeComponent();
        }
        //private FormProcess Frp;
        private string MaSP1, TenSP1,SoBB1, SoHD1,KhachHang1,DVGC1,LoaiGo1, SLNhap1, Ngay_start1, Ngay_End1, child = " - ", Ngay1, NgayInsert1, UserNhap,SoThung1,LyDo1,GhiChu1,DVT1,ChungTu1,ArticleNumber1,IDNumber1,ViTri1,string_temp,check,Kien1;
        private double Tong1 = 0, SLNhap_d = 0, SLXuat_d = 0, SoThung_d,TK_KTP=0;
        private int i = 0, j = 0, k = 0, check_number=0, Pallet_d = 0, Topfiller_d = 0, Sidefiller_d = 0, other_d = 0;
        private void combo_load()
        {
            Data dta = new Data();
            FormProcess Frp = new FormProcess();
            string sql_load = @"select MaSP,TenSP from dbo.Load_cbSP";
            SqlConnection Conn = dta.Connect();
            SqlCommand cmd = new SqlCommand();
            
            Conn.Open();
            cmd.Connection = Conn;
            cmd.CommandText = sql_load;
            try
            {
                SqlDataReader rd = cmd.ExecuteReader();
                while (rd.Read())
                {
                    cb_MaSPinput.Items.Add(rd[1].ToString() + " - " + rd[0].ToString());
                    cb_MaSPoutput.Items.Add(rd[1].ToString() + " - " + rd[0].ToString());
                    cb_MaSPTK.Items.Add(rd[1].ToString() + " - " + rd[0].ToString());
                    cb_MaSPReport.Items.Add(rd[1].ToString() + " - " + rd[0].ToString());
                    cb_TenSP_VT.Items.Add(rd[1].ToString() + " - " + rd[0].ToString());
                    cb_MaSP_TKVT.Items.Add(rd[1].ToString() + " - " + rd[0].ToString());
                    cb_MaSPHC.Items.Add(rd[1].ToString() + " - " + rd[0].ToString());
                    cb_MaSPHCVT.Items.Add(rd[1].ToString() + " - " + rd[0].ToString());
                    cb_MaSP_VTS.Items.Add(rd[1].ToString() + " - " + rd[0].ToString());
                    cb_MaSP_Editinput.Items.Add(rd[1].ToString() + " - " + rd[0].ToString());
                }
                rd.Close();

                sql_load = @"Select convert(char(10),NgayDongKy,103) from dbo.closeout where KhuVuc='KhoTP' and datediff(dd,NgayDongKy,getdate())<100";
                cmd.CommandText = sql_load;
                rd = cmd.ExecuteReader();
                while (rd.Read())
                {
                    cb_Closeout.Items.Add(rd[0].ToString());
                   //lb_Date_input.Text = rd[1].ToString();
                  
                   // MessageBox.Show(rd[1].ToString());
                    //string_temp=rd[1].ToString();
                }
                //MessageBox.Show(rd[1].ToString());
               
                sql_load = @"select MaLyDo,LyDo from dbo.LyDo where KV='KhoTP'";

                Frp.cb1(cb_LyDoNhap, sql_load, 1, 0);
                Frp.cb1(cb_LyDoXuat, sql_load, 1, 0);
                Frp.cb1(cb_LyDo_Editinput, sql_load, 1, 0);

                string[] arr = new string[] { "Cái", "Thùng", "Kg", "Thanh", "Bịch", "Đồng" };
                for (i = 0; i < arr.Length; i++)
                {
                    cb_DVTinput.Items.Add(arr[i].ToString());
                    cb_DVToutput.Items.Add(arr[i].ToString());
                }
                cb_LyDoNhap.Text = "NHAP MOI - TPNM";
                cb_LyDoXuat.Text = "XUAT BAN - TPXB";

                string[] arr1 = new string[] { "ac", "eu" };
                for (i = 0; i < arr1.Length; i++)
                {
                    cb_LoaiGoinput.Items.Add(arr1[i].ToString());
                    cb_LoaiGooutput.Items.Add(arr1[i].ToString());
                    cb_LoaiGo_HC.Items.Add(arr1[i].ToString());
                }
                string[] arr3 = new string[] { "Pallet", "TopFiller", "SideFiller", "Piece" };
                for (i = 0; i < arr3.Length; i++)
                {
                    cb_Kieninput.Items.Add(arr3[i].ToString());

                }
                cb_Kieninput.Text = "Pallet";
                cb_KhachHanginput.Items.Add("IKEA");
                cb_KhachHangoutput.Items.Add("IKEA");
                string[] arr2 = new string[] { "Vũ Dinh", "Sơn Việt Hùng", "Sài Gòn Viễn Đông", "Huy Hoàng Phát", "BiTiCo", "Huế" };
                for (i = 0; i < arr2.Length; i++)
                {
                    cb_DVGCinput.Items.Add(arr2[i].ToString());
                    cb_DVGCoutput.Items.Add(arr2[i].ToString());
                }
                sql_load = @"select TenSP+' - '+MaSP as MaSP,ArticleNumber,SLuong,[TopFilller],[SideFiller],[Other],SLPallet,SLTopfiller,SLSidefiller,SLOther from dbo.ArticleNumberProduct where ArticleNumber is not null";
                DataSet ds = dta.dts(sql_load);
                dataGridView7.DataSource = ds.Tables[0];
                sql_load = @"SELECT  [ViTri] FROM [dbo].[KhoTP_SoDo] ";
                cmd.CommandText = sql_load;
                rd.Close();
                rd = cmd.ExecuteReader();
                while (rd.Read())
                {
                    cb_ViTriinput.Items.Add(rd[0].ToString());
                    cb_ViTrioutput.Items.Add(rd[0].ToString());
                    txt_ViTriVT.Items.Add(rd[0].ToString());
                    txt_ViTri_Chuyenoutput.Items.Add(rd[0].ToString());
                    cb_ViTri_TKVT.Items.Add(rd[0].ToString());
                    cb_ViTriHCVT.Items.Add(rd[0].ToString());
                    cb_VTSA.Items.Add(rd[0].ToString());
                    cb_VTSB.Items.Add(rd[0].ToString());
                }
                rd.Close();
                sql_load = @"select MaSP,ViTri from dbo.KhoTP_NK where DATEDIFF(dd,NgayInsert,getdate())<2";
                cmd.CommandText = sql_load;
                rd = cmd.ExecuteReader();
                while (rd.Read())
                {
                    dataGridView6.Rows.Add(rd[0].ToString(), rd[1].ToString());
                }
                rd.Close();
                string[] arr4 = new string[] { "Chuẩn", "Khác" };
                for (i = 0; i < arr4.Length; i++)
                {
                    cb_KieuXuat.Items.Add(arr4[i].ToString());
                }
                get_columns_gridoutput();
                ThongTin();
                arr.Clone();
                arr1.Clone();
                arr2.Clone();
                arr3.Clone();
                arr4.Clone();
                Conn.Close();
                cmd.Dispose();
               


            }
            catch (Exception ex)
            { MessageBox.Show("Lỗi load Combobox " + ex.Message); }
            
        }
        public void checktext_number(TextBox txt)
        {
            try
            {
                if (txt.Text.Length > 0)
                {
                    txt.Text = double.Parse(txt.Text).ToString();//ép kiểu float,nếu xảy ra ngoại lệ thì bẫy lỗi ở hàm checktext_number
                    txt.SelectionStart = txt.Text.Length;
                }
            }
            catch (Exception ex)//Bẫy lỗi khi nhập chữ vào text box
            {
                string s = "Input string";
                if (ex.Message.ToString().Contains(s))
                {
                    MessageBox.Show("Giá trị nhập phải là số");
                    txt.Text = "";
                }
                else
                    MessageBox.Show(ex.Message);
            }
        }
        private void Enable()
        {
            tab_Nhap.Visible = true;
            tab_Xuat.Visible = true;
            tab_ViTri.Visible = true;
        }
        private void Disable()
        {
            tab_Nhap.Visible = false;
            tab_Xuat.Visible = false;
            tab_ViTri.Visible = false;
        }
        private void Check_User()
        {
            Process prs = new Process();
            SqlConnection Conn = prs.Connect();
            SqlCommand cmd = new SqlCommand();
            try
            {
                Conn.Open();
                string check = @"select GroupUser from dbo.Users where UsersName='" + lb_user.Text + "'";
                cmd.Connection = Conn;
                cmd.CommandText = check;
                //MessageBox.Show(check);
                check = cmd.ExecuteScalar().ToString();
                if (check == "thongke" || check == "admin" || check == "nhaplieu")
                    Enable();
                else
                    Disable();
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
            finally
            {
                Conn.Close();
                cmd.Dispose();
            }
        }

        private void txt_SLinput_TextChanged(object sender, EventArgs e)
        {
            FormProcess Frp = new FormProcess();
            Frp.checktext_number(txt_SLinput);
        }

        private void txt_SoThunginput_TextChanged(object sender, EventArgs e)
        {
            checktext_number(txt_SoThunginput);
        }

        private void FrKhoThanhPham_Load(object sender, EventArgs e)
        {
            combo_load();
           
            
        }
        private void add_grid()
        {
            try
            {
                Process prs = new Process();
                TenSP1 = prs.substring_left(cb_MaSPinput.Text, child);
                MaSP1 = prs.substring_right(cb_MaSPinput.Text, child);
                LoaiGo1 = cb_LoaiGoinput.Text;
                IDNumber1 = txt_IDNumberinput.Text.Trim();
                ArticleNumber1 = txt_ArticleNumberinput.Text.Trim();
                LyDo1 = prs.substring_right(cb_LyDoNhap.Text, child);
                Kien1 = cb_Kieninput.Text.Trim();
                Ngay_End1 = txt_Ngayinput.Text;
                for (i = 0; i < cb_Closeout.Items.Count; i++)
                {
                    if (Ngay_End1 == cb_Closeout.Items[i].ToString())
                    {
                        Ngay_End1 = "C";
                        break;
                    }
                    
                }
                if (MaSP1==""|| txt_SLinput.Text == ""||txt_SoThunginput.Text==""||LyDo1==""||cb_LoaiGoinput.Text==""||txt_SoHDinput.Text==""||ArticleNumber1==""||IDNumber1==""||cb_ViTriinput.Text==""||cb_Kieninput.Text==""||Ngay_End1=="C")
                {
                    if (Ngay_End1 == "C")
                        MessageBox.Show("Ngày " + txt_Ngayinput.Text + " đã khóa sổ, vui lòng kiểm tra lại");
                    else
                        MessageBox.Show("Thông Tin Nhập Không Chính Xác Hoặc Thiếu");
                }
                else
                {
                    i = 0;
                    if (dataGridView1.Rows.Count > 1)
                    {
                        while (i < dataGridView1.Rows.Count - 1)
                        {
                            if (IDNumber1!=dataGridView1.Rows[i].Cells["IDNumberinput"].Value.ToString())
                                i++;
                            else
                                break;
                        }
                    }
                    if (dataGridView1.Rows.Count == 1 || i == dataGridView1.Rows.Count - 1)
                    {
                        k = cb_MaSPinput.Items.Count - 1;
                        while (k >= 0)
                        {

                            if (MaSP1 == prs.substring_right(cb_MaSPinput.Items[k].ToString(), child))
                                break;
                            else
                                k--;
                        }
                        j = cb_LoaiGoinput.Items.Count - 1;
                        //MessageBox.Show(LoaiGo1);
                        
                        while (j >= 0)
                        {
                            if (LoaiGo1 == cb_LoaiGoinput.Items[j].ToString())
                                break;
                            else
                                j--;
                        }
                        check_number = cb_Kieninput.Items.Count - 1;
                        while (check_number >= 0)
                        {
                            if(Kien1==cb_Kieninput.Items[check_number].ToString())
                                break;
                            else
                                check_number--;

                        }
                       // MessageBox.Show(j.ToString());
                        if (k >= 0&&j>=0&&check_number>=0)
                        {
                            DVGC1 = cb_DVGCinput.Text;
                            SoHD1 = txt_SoHDinput.Text;
                            SoBB1 = txt_SoBBinput.Text.Trim();
                            KhachHang1 = cb_KhachHanginput.Text;
                            LoaiGo1 = cb_LoaiGoinput.Text;
                            SoThung_d = double.Parse(txt_SoThunginput.Text);
                           
                            SLNhap1 = txt_SLinput.Text;
                            if (date_default.Checked == false)
                            {
                                Ngay1 = txt_Ngayinput.Text.Trim();
                                string[] temp = txt_Ngayinput.Text.Split('/');
                                NgayInsert1 = temp[1] + "/" + temp[0] + "/" + temp[2];
                            }
                            if (date_default.Checked == true)
                            {
                                Ngay1 = lb_Date_input.Text.Trim();
                                string[] temp = lb_Date_input.Text.Split('/');
                                NgayInsert1 = temp[1] + "/" + temp[0] + "/" + temp[2];
                                //NgayInsert1 = lb_Date_input.Text;
                            }
                            GhiChu1 = txt_GhiChuinput.Text;
                            DVT1 = cb_DVTinput.Text.Trim();
                            ViTri1 = cb_ViTriinput.Text.Trim();
                           
                            dataGridView1.Rows.Add(MaSP1, TenSP1, LoaiGo1, SLNhap1, DVT1, SoThung_d,ArticleNumber1,IDNumber1,ViTri1, LyDo1, KhachHang1,Kien1, Ngay1, SoBB1, DVGC1, SoHD1, NgayInsert1, GhiChu1);
                            dataGridView6.Rows.Add(MaSP1, ViTri1);
                            j = dataGridView1.Rows.Count - 1;
                            dataGridView1.CurrentCell = dataGridView1.Rows[j].Cells[0];
                            dataGridView1.FirstDisplayedCell = dataGridView1.Rows[j].Cells[0];
                            
                           //dataGridView1.Cu
                            prs.formatcolordatagrid(dataGridView1);
                            //prs.reset_txt(groupPanel1);
                            txt_SLinput.Text = "";
                            cb_MaSPinput.Text = "";
                            txt_GhiChuinput.Text = "";
                            txt_SoThunginput.Text = "";
                            //txt_SoBBinput.Text = "";
                            Tong1 = double.Parse(lb_Tong.Text);
                            Tong1 += double.Parse(SLNhap1);
                            lb_Tong.Text = Tong1.ToString();
                            lb_Tong.Text = string.Format("{0:###,###}", Tong1);
                            txt_IDNumberinput.Text = "";
                            txt_ArticleNumberinput.Text = "";
                            txt_ArticleNumberinput.Focus();                       
                        }
                        else
                            MessageBox.Show("Kiểm tra lại Mã CT hoặc Mã KH nhập");
                    }
                    else
                        MessageBox.Show("ArticleNumber hoặc IDNumber này đã có trong DS phía dưới");
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
               
        }
        #region //Bat su kien checbox change checked trong datagrid view
        private void dataGridView9_CellValueChanged(object sender, DataGridViewCellEventArgs e)
        {
            try
            {

                if (e.ColumnIndex == 0) //compare to checkBox column index
                {
                    DataGridViewCheckBoxCell chk = (DataGridViewCheckBoxCell)dataGridView9[e.ColumnIndex, e.RowIndex];
                    check = dataGridView9.Rows[e.RowIndex].Cells["ViTri_TK"].Value.ToString();

                    if (!DBNull.Value.Equals(chk.Value) && chk.Value == chk.TrueValue)
                    {
                        cb_ViTriinput.Text = check;
                        tab_control.SelectedTab = tab_Nhap;

                    }

                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }

        private void dataGridView9_CurrentCellDirtyStateChanged(object sender, EventArgs e)
        {
            if (dataGridView9.IsCurrentCellDirty)
                dataGridView9.CommitEdit(DataGridViewDataErrorContexts.Commit);
        }
        #endregion
        private void bt_insertinput_Click(object sender, EventArgs e)
        {
            add_grid();
        }
        private void save_input()
        {
            Data dta = new Data();
            SqlConnection Conn = dta.Connect();
            SqlCommand cmd = new SqlCommand();
            //
            cmd.CommandType = CommandType.StoredProcedure;
            Conn.Open();
            cmd.Connection = Conn;
            
            try
            {
                SoHD1 = txt_SoHDinput.Text.Trim();
                SoBB1 = txt_SoBBinput.Text.Trim();

                cmd.CommandText = "Ins_ChungTuKTP";
                cmd.Parameters.AddWithValue("@check", "0");
                cmd.Parameters.AddWithValue("@MaKH", KhachHang1);
                cmd.Parameters.AddWithValue("@HieuChinh", "0");
                cmd.Parameters.AddWithValue("@SoBB", SoBB1);
                cmd.Parameters.AddWithValue("@SoHD", SoHD1);
                //cmd.Parameters.AddWithValue("@Checked", "-1");
                SqlParameter code = new SqlParameter("@MaCT", SqlDbType.Int);
                code.Direction = ParameterDirection.Output;
                cmd.Parameters.Add(code);
                SqlDataReader sdr = cmd.ExecuteReader();
                ChungTu1 = cmd.Parameters["@MaCT"].Value.ToString();
                sdr.Close();
                cmd.Parameters.Clear();
                cmd.CommandText = "Ins_KTPNK";
                if (dataGridView1.Rows.Count > 1)
                {
                    UserNhap = lb_user.Text;
                    for (i = dataGridView1.Rows.Count - 2; i >= 0; i--)
                    {
                        MaSP1 = dataGridView1.Rows[i].Cells["MaSPinput"].Value.ToString();
                        SoHD1 = dataGridView1.Rows[i].Cells["SoHDinput"].Value.ToString();
                        KhachHang1 = dataGridView1.Rows[i].Cells["KhachHanginput"].Value.ToString();
                        LoaiGo1 = dataGridView1.Rows[i].Cells["LoaiGoinput"].Value.ToString();
                        DVGC1 = dataGridView1.Rows[i].Cells["DVGCinput"].Value.ToString();
                        SoBB1 = dataGridView1.Rows[i].Cells["SoBBinput"].Value.ToString();
                        SLNhap_d = double.Parse(dataGridView1.Rows[i].Cells["SLinput"].Value.ToString());
                        SoThung1 = dataGridView1.Rows[i].Cells["SLThunginput"].Value.ToString();
                        ArticleNumber1 = dataGridView1.Rows[i].Cells["ArticleNumberinput"].Value.ToString();
                        IDNumber1 = dataGridView1.Rows[i].Cells["IDNumberinput"].Value.ToString();
                        ViTri1 = dataGridView1.Rows[i].Cells["ViTriinput"].Value.ToString();
                        DVT1 = dataGridView1.Rows[i].Cells["DVTinput"].Value.ToString();
                        Ngay1 = dataGridView1.Rows[i].Cells["NgayInsertinput"].Value.ToString();
                        GhiChu1 = dataGridView1.Rows[i].Cells["GhiChuinput"].Value.ToString();    
                        LyDo1 = dataGridView1.Rows[i].Cells["LyDoinput"].Value.ToString();
                        Kien1 = dataGridView1.Rows[i].Cells["Kieninput"].Value.ToString();
                        cmd.Parameters.AddWithValue("@ChungTu", ChungTu1);
                        cmd.Parameters.AddWithValue("@MaSP", MaSP1);
                        cmd.Parameters.AddWithValue("@ArticleNumber", ArticleNumber1);
                        cmd.Parameters.AddWithValue("@IDNumber", IDNumber1);
                        cmd.Parameters.AddWithValue("@ViTri", ViTri1);
                        cmd.Parameters.AddWithValue("@SoHD", SoHD1);
                        cmd.Parameters.AddWithValue("@KhachHang", KhachHang1);
                        cmd.Parameters.AddWithValue("@LoaiGo", LoaiGo1);
                        cmd.Parameters.AddWithValue("@DVGC", DVGC1);
                        cmd.Parameters.AddWithValue("@SoBB", SoBB1);
                        cmd.Parameters.AddWithValue("@SLNhap", SLNhap_d);
                        cmd.Parameters.AddWithValue("@SLThungNhap", SoThung1);
                        cmd.Parameters.AddWithValue("@DVT", DVT1);
                        cmd.Parameters.AddWithValue("@Ngay", Ngay1);
                        cmd.Parameters.AddWithValue("@UserNhap", UserNhap);
                        cmd.Parameters.AddWithValue("@GhiChu", GhiChu1);
                        cmd.Parameters.AddWithValue("@LyDo", LyDo1);
                        cmd.Parameters.AddWithValue("@Kien", Kien1);
                        cmd.ExecuteNonQuery();
                        cmd.Parameters.Clear();
                        dataGridView1.Rows.RemoveAt(i);
                    }
                    MessageBox.Show("Dữ Liệu được lưu thành công");
                    lb_Tong.Text = "0";
                    txt_GhiChuinput.Text = "";
                    txt_SLinput.Text = "";
                    txt_SoBBinput.Text = "";
                    txt_SoThunginput.Text = "";
                    cb_DVGCinput.Text = "";
                    
                    txt_ArticleNumberinput.Text = "";
                    txt_IDNumberinput.Text = "";
                    cb_ViTriinput.Text = "";
                    cb_LyDoNhap.Text = "NHAP MOI - TPNM";
                    cb_LyDoNhap.Enabled = false;
                    lb_Articlenumber.Text = "Article Number";
                    txt_ArticleNumberinput.Focus();
                }



            }
            catch (Exception ex)
            {
                string s = "insert duplicate key";
                string FK = "FOREIGN KEY constraint";
                string s1 = ex.Message.ToString();
                if (s1.Contains(s))
                { MessageBox.Show("Insert không thành công \n" + "Mã đã tồn tại "); }
                else if (s1.Contains(FK))
                {
                    MessageBox.Show("Nhập sai thông tin trong Combobox");
                }
                else
                    MessageBox.Show(ex.Message);
                MessageBox.Show("Đã xảy ra lỗi khi thêm dữ liệu, vui lòng kiểm tra lại");
            }
            finally
            {
                Conn.Close();
                cmd.Dispose();
            }
        }

        private void bt_saveinput_Click(object sender, EventArgs e)
        {
            save_input();
        }
        private void edit_input()
        {
            string datecheck;
            int date_count;
            Process prs = new Process();
            SqlConnection Conn = prs.Connect();
            SqlCommand cmd = new SqlCommand();
            try
            {

                DialogResult d = MessageBox.Show("Bạn có chắc muốn sửa Thông Tin có Số Serial " + lb_serialinput.Text, "Thông Báo", MessageBoxButtons.OKCancel);
                if (cb_Kieninput.Text == "")
                    MessageBox.Show("Thiếu loại kiện");
                else
                {
                    MaSP1 = prs.substring_right(cb_MaSPinput.Text, child);
                    ViTri1 = cb_ViTriinput.Text;
                    DVGC1 = cb_DVGCinput.Text;
                    SoHD1 = txt_SoHDinput.Text;
                    SoBB1 = txt_SoBBinput.Text.Trim();
                    KhachHang1 = cb_KhachHanginput.Text;
                    LoaiGo1 = cb_LoaiGoinput.Text;
                    SoThung_d = double.Parse(txt_SoThunginput.Text);
                    Kien1 = cb_Kieninput.Text.Trim();
                    string[] temp = txt_Ngayinput.Text.Split('/');
                    Ngay1 = temp[1] + "/" + temp[0] + "/" + temp[2];
                    
                    GhiChu1 = txt_GhiChuinput.Text;
                    DVT1 = cb_DVTinput.Text.Trim();
                    LyDo1 = prs.substring_right(cb_LyDoNhap.Text, child);
                    if (LyDo1 == "")
                        LyDo1 = cb_LyDoNhap.Text;

                    SLNhap_d = double.Parse(txt_SLinput.Text);
                    GhiChu1 = txt_GhiChuinput.Text;

                    Conn.Open();
                    cmd.Connection = Conn;
                    datecheck = @"select datediff(dd,NgayInsert,getdate()) from dbo.KhoTP_NK where Serial='" + lb_serialinput.Text + "'";
                    if (d == DialogResult.OK)
                    {
                        cmd.CommandText = datecheck;
                        date_count = int.Parse(cmd.ExecuteScalar().ToString());
                        if (date_count <= 1||lb_user.Text=="administrator")
                        {
                            cmd.CommandText = "Upd_KTPNK";
                            cmd.CommandType = CommandType.StoredProcedure;
                            cmd.Parameters.AddWithValue("@MaSP", MaSP1);
                            cmd.Parameters.AddWithValue("@SoHD", SoHD1);
                            cmd.Parameters.AddWithValue("@KhachHang", KhachHang1);

                            cmd.Parameters.AddWithValue("@LoaiGo", LoaiGo1);
                            cmd.Parameters.AddWithValue("@DVGC", DVGC1);
                            cmd.Parameters.AddWithValue("@SoBB", SoBB1);
                            cmd.Parameters.AddWithValue("@SLNhap", SLNhap_d);
                            cmd.Parameters.AddWithValue("@SLThungNhap", SoThung_d);

                            cmd.Parameters.AddWithValue("@DVT", DVT1);
                            cmd.Parameters.AddWithValue("@Ngay", Ngay1);
                            cmd.Parameters.AddWithValue("@Useredit", lb_user.Text);
                            cmd.Parameters.AddWithValue("@GhiChu", GhiChu1);
                            cmd.Parameters.AddWithValue("@LyDo", LyDo1);
                            cmd.Parameters.AddWithValue("@Serial", lb_serialinput.Text);
                            cmd.Parameters.AddWithValue("@Kien", Kien1);
                            cmd.ExecuteNonQuery();

                            MessageBox.Show("Chỉnh Sửa Thành Công");
                            cb_LyDoNhap.Text = "NHAP MOI - TPNM";
                            cb_LyDoNhap.Enabled = false;
                        }
                        else
                            MessageBox.Show("Không được phép chỉnh sửa");

                        for (int i = 0; i < dataGridView2.Rows.Count - 1; i++)
                        {
                            dataGridView2.Rows.RemoveAt(0);
                        }
                        prs.reset_txt(groupPanel1);
                        bt_editinput.Enabled = false;
                        bt_deleteinput.Enabled = false;
                        lb_serialinput.Text = "0";
                        //date_default.Checked = true;
                        string[] temp1 = lb_Date_input.Text.Split('/');
                        Ngay1 = temp1[1] + "/" + temp1[0] + "/" + temp1[2];
                        txt_Ngayinput.Text = Ngay1;
                        temp1.Clone();
                        temp.Clone();
                    }
                }
            }
            catch (Exception ex)
            {
                string s = "The conversion of a char data type to a datetime";
                string s1 = ex.Message.ToString();
                if (s1.Contains(s))
                { MessageBox.Show("Ngày Tháng Nhập chưa đúng"); }
                MessageBox.Show(ex.Message);
            }
            finally
            {
                Conn.Close();
                cmd.Dispose();
            }


        }
        private void Display_Input(int i)
        {
            try
            {
                MaSP1 = dataGridView2.Rows[i].Cells["MaSP"].Value.ToString();
                TenSP1 = dataGridView2.Rows[i].Cells["TenSP"].Value.ToString();
               
                cb_MaSPinput.Text = TenSP1 + " - " + MaSP1;
                
                txt_SoHDinput.Text = dataGridView2.Rows[i].Cells["SoHD"].Value.ToString();
                cb_KhachHanginput.Text = dataGridView2.Rows[i].Cells["KhachHang"].Value.ToString();
                cb_LoaiGoinput.Text = dataGridView2.Rows[i].Cells["LoaiGo"].Value.ToString();
                cb_DVGCinput.Text = dataGridView2.Rows[i].Cells["DVGC"].Value.ToString();
                txt_SoBBinput.Text = dataGridView2.Rows[i].Cells["SoBB"].Value.ToString();
              
                txt_SLinput.Text = dataGridView2.Rows[i].Cells["SLNhap"].Value.ToString();
                txt_SoThunginput.Text = dataGridView2.Rows[i].Cells["SLThungNhap"].Value.ToString();
                cb_DVTinput.Text = dataGridView2.Rows[i].Cells["DVT"].Value.ToString();
                txt_Ngayinput.Text = dataGridView2.Rows[i].Cells["Ngay"].Value.ToString();
                lb_serialinput.Text = dataGridView2.Rows[i].Cells["Serial"].Value.ToString();
                cb_LyDoNhap.Text = dataGridView2.Rows[i].Cells["LyDo"].Value.ToString();
                txt_GhiChuinput.Text = dataGridView2.Rows[i].Cells["GhiChu"].Value.ToString();
                txt_ArticleNumberinput.Text = dataGridView2.Rows[i].Cells["ArticleNumber"].Value.ToString();
                txt_IDNumberinput.Text = dataGridView2.Rows[i].Cells["IDNumber"].Value.ToString();
                cb_ViTriinput.Text = dataGridView2.Rows[i].Cells["ViTri"].Value.ToString();
                cb_Kieninput.Text = dataGridView2.Rows[i].Cells["Kien"].Value.ToString();
                cb_ViTriinput.Enabled = false;

            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }
        private void search_Input()
        {
            try
            {
                string search = null;
                Process prs = new Process();
                DataSet ds = new DataSet();
                if (txt_IDNumberinput.Text == "")
                {
                    if (cb_MaSPinput.Text != "" && txt_Ngayinput.Text != "")
                    {
                        MaSP1 = prs.substring_right(cb_MaSPinput.Text, child);
                        string[] temp = txt_Ngayinput.Text.Split('/');
                        Ngay1 = temp[1] + "/" + temp[0] + "/" + temp[2];
                    }
                    if (MaSP1 == "")
                        MessageBox.Show("Mã SP không chính xác");
                    else
                    {
                        search = @"select dbo.KhoTP_NK.*,dbo.Load_cbSP.TenSP from dbo.KhoTP_NK inner join dbo.Load_cbSP on KhoTP_NK.MaSP=dbo.Load_cbSP.MaSP
                                where SLNhap>0 and Ngay='" + Ngay1 + "'and dbo.Load_cbSP.MaSP='" + MaSP1 + "'  order by dbo.KhoTP_NK.Serial";
                    }
                }
                else
                {

                    search = @"select dbo.KhoTP_NK.*,dbo.Load_cbSP.TenSP from dbo.KhoTP_NK inner join dbo.Load_cbSP on KhoTP_NK.MaSP=dbo.Load_cbSP.MaSP
                                where SLNhap>0 and IDNumber='" + txt_IDNumberinput.Text.Trim() + "' order by dbo.KhoTP_NK.Serial";
                }
               
                ds = prs.dts(search);
                if (ds.Tables[0].Rows.Count == 0)
                    MessageBox.Show("Không có dữ liệu, vui lòng kiểm tra lại thông tin tìm kiếm");
                else
                {
                    dataGridView2.DataSource = ds.Tables[0];
                    int k = dataGridView2.Rows.Count - 2;
                    Display_Input(k);
                    lb_index.Text = k.ToString();
                    bt_editinput.Enabled = true;
                    bt_deleteinput.Enabled = true;
                    bt_insertinput.Enabled = false;
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }

        private void bt_searchinput_Click(object sender, EventArgs e)
        {
            search_Input();
        }

        private void bt_previnput_Click(object sender, EventArgs e)
        {
            try
            {
                if (dataGridView2.Rows.Count > 1)
                {
                    int i;
                    i = int.Parse(lb_index.Text);
                    if (i > 0)
                    {
                        i--;
                        Display_Input(i);
                        lb_index.Text = i.ToString();
                    }
                }
            }
            catch (Exception ex)
            { MessageBox.Show(ex.Message); }
        }

        private void bt_nextinput_Click(object sender, EventArgs e)
        {
            try
            {
                if (dataGridView2.Rows.Count > 1)
                {
                    int i;
                    i = int.Parse(lb_index.Text);
                    if (i < dataGridView2.Rows.Count - 2)
                    {
                        i++;
                        Display_Input(i);
                        lb_index.Text = i.ToString();
                    }
                }
            }
            catch (Exception ex)
            { MessageBox.Show(ex.Message); }
        }

        private void bt_editinput_Click(object sender, EventArgs e)
        {
            edit_input();
        }

        private void bt_deleteinput_Click(object sender, EventArgs e)
        {
            DialogResult d = MessageBox.Show("Bạn có chắc muốn xóa Thông Tin có Số Serial " + lb_serialinput.Text, "Thông Báo", MessageBoxButtons.OKCancel);
            if (d == DialogResult.OK)
            {
                try
                {
                    string datecheck = @"select datediff(dd,NgayInsert,getdate()) from dbo.KhoTP_NK where Serial='" + lb_serialinput.Text + "'";
                    //string delete = @"delete from dbo.KhoTP_NK where Serial='" + lb_serialinput.Text + "'";
                    Data dta = new Data();
                    SqlConnection Conn = dta.Connect();
                    Conn.Open();
                    SqlCommand cmd = new SqlCommand();
                    cmd.Connection = Conn;
                    cmd.CommandText = datecheck;
                    int date_count = int.Parse(cmd.ExecuteScalar().ToString());
                    if (date_count <= 1 || lb_user.Text == "administrator")
                    {
                        cmd.CommandType = CommandType.StoredProcedure;
                        cmd.CommandText = "Tran_Del_Up_NKTP";
                        cmd.Parameters.AddWithValue("@Serial", lb_serialinput.Text);
                        cmd.Parameters.AddWithValue("@ViTri", cb_ViTriinput.Text);
                       
                        cmd.ExecuteNonQuery();
                        MessageBox.Show("Dữ liệu được xóa thành công");

                        lb_serialinput.Text = "0";
                    }
                    else
                    {
                        MessageBox.Show("Quá thời gian cho phép,Không được phép xóa");
                    }
                    Conn.Close();
                    cmd.Dispose();
                    for (int i = dataGridView2.Rows.Count - 2; i >=0; i--)
                    {
                        dataGridView2.Rows.RemoveAt(i);
                    }
                    dta.reset_txt(groupPanel1);
                    bt_deleteinput.Enabled = false;
                    bt_editinput.Enabled = false;
                    Conn.Close();
                    cmd.Dispose();
                }
                catch (Exception ex)
                {

                    string FK = "REFERENCE constraint";
                    string s1 = ex.Message.ToString();
                    if (s1.Contains(FK))
                    { MessageBox.Show("Kiện hàng này có thể đã xuất rồi, Xóa không được, vui lòng kiểm tra lại"); }
                    MessageBox.Show(ex.Message);
                }
            }
        }

     
        private void add_grid_out()
        {
            #region //Dung trong truong hop add tung dong
            try
            {
                Process prs = new Process();
                TenSP1 = prs.substring_left(cb_MaSPoutput.Text, child);
                MaSP1 = prs.substring_right(cb_MaSPoutput.Text, child);
                LoaiGo1 = cb_LoaiGooutput.Text.Trim();
                LyDo1 = prs.substring_right(cb_LyDoXuat.Text, child);
                IDNumber1 = txt_IDNumberoutput.Text.Trim();
                ArticleNumber1 = txt_ArticleNumberoutput.Text.Trim();
                if (MaSP1 == "" || txt_SLoutput.Text == "" || txt_SLThungoutput.Text == "" || LyDo1 == "" || cb_LoaiGooutput.Text == "" || txt_SoHDoutput.Text == ""||IDNumber1==""||ArticleNumber1=="")
                {
                    MessageBox.Show("Thông Tin Nhập Không Chính Xác Hoặc Thiếu");
                }
                else
                {
                    i = 0;
                    if (dataGridView3.Rows.Count > 1)
                    {
                        while (i < dataGridView3.Rows.Count - 1)
                        {
                            if (IDNumber1!=dataGridView3.Rows[i].Cells["IDNumberoutput"].Value.ToString())
                                i++;
                            else
                                break;
                        }
                    }
                    if (dataGridView3.Rows.Count == 1 || i == dataGridView3.Rows.Count - 1)
                    {
                        k = cb_MaSPoutput.Items.Count - 1;
                        while (k >= 0)
                        {
                            if (MaSP1 == prs.substring_right(cb_MaSPoutput.Items[k].ToString(), child))
                                break;
                            else
                                k--;
                        }
                        j = cb_LoaiGooutput.Items.Count - 1;
                        while(j>=0)
                        {
                            if (LoaiGo1 == cb_LoaiGooutput.Items[j].ToString())
                                break;
                            else
                                j--;
                        }
                        if (k >= 0&&j>=0)
                        {
                            DVGC1 = cb_DVGCoutput.Text;
                            SoHD1 = txt_SoHDoutput.Text;
                            SoBB1 = txt_SoBBoutput.Text.Trim();
                            KhachHang1 = cb_KhachHangoutput.Text;
                            LoaiGo1 = cb_LoaiGooutput.Text.Trim();
                            SoThung_d = double.Parse(txt_SLThungoutput.Text);
                            Ngay1 = txt_Ngayoutput.Text.Trim();
                            SLNhap1 = txt_SLoutput.Text;
                            ViTri1 = cb_ViTrioutput.Text.Trim();
                            string[] temp = txt_Ngayoutput.Text.Split('/');
                            NgayInsert1 = temp[1] + "/" + temp[0] + "/" + temp[2];
                            GhiChu1 = txt_GhiChuoutput.Text;
                            DVT1 = cb_DVToutput.Text.Trim();
                            dataGridView3.Rows.Add(false, MaSP1, TenSP1, LoaiGo1, SLNhap1, DVT1, SoThung_d, ArticleNumber1, IDNumber1, ViTri1, LyDo1, KhachHang1, Ngay1, SoBB1, DVGC1, SoHD1, NgayInsert1, GhiChu1);
                            j = dataGridView3.Rows.Count - 1;
                            dataGridView3.CurrentCell = dataGridView3.Rows[j].Cells[0];
                            dataGridView3.FirstDisplayedCell = dataGridView3.Rows[j].Cells[0];
                            prs.formatcolordatagrid(dataGridView3);
                            //prs.reset_txt(groupPanel1);
                            txt_SLoutput.Text = "";
                            cb_MaSPoutput.Text = "";
                            txt_GhiChuoutput.Text = "";
                            txt_SLThungoutput.Text = "";
                            txt_SoBBoutput.Text = "";
                            cb_LoaiGooutput.Text = "";
                            Tong1 = double.Parse(lb_TongXuat.Text);
                            Tong1 += double.Parse(SLNhap1);
                            lb_TongXuat.Text = Tong1.ToString();
                            lb_TongXuat.Text = string.Format("{0:###,###}", Tong1);

                            cb_MaSPoutput.Focus();

                        }
                        else
                            MessageBox.Show("Kiểm tra lại Mã Sản Phẩm hoặc Loại Gỗ nhập");
                    }
                    else
                        MessageBox.Show("Sản Phẩm hoặc IDNumber này đã có trong DS phía dưới");
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
            #endregion

        }

        private void bt_insertoutput_Click(object sender, EventArgs e)
        {
            add_grid_out();
        }
        private void save_output()
        {
            int i;
            Data dta = new Data();
            SqlConnection Conn = dta.Connect();
            SqlCommand cmd = new SqlCommand();
            Conn.Open();
            cmd.Connection = Conn;
            cmd.CommandType = CommandType.StoredProcedure;
            ChungTu1 = "0";
            try
            {
                UserNhap = lb_user.Text;
                KhachHang1 = cb_KhachHangoutput.Text.Trim();
                if (dataGridView3.Rows.Count > 1)
                {
                    if (txt_SoCT.Enabled == false)
                    {
                        cmd.CommandText = "Ins_ChungTuKTP";
                        
                        SoBB1=txt_SoBBoutput.Text.Trim();
                        SoHD1 = txt_SoHDoutput.Text.Trim();
                        cmd.Parameters.AddWithValue("@check", "0");
                        cmd.Parameters.AddWithValue("@MaKH", KhachHang1);
                        cmd.Parameters.AddWithValue("@HieuChinh", "0");
                        cmd.Parameters.AddWithValue("@SoBB", SoBB1);
                        cmd.Parameters.AddWithValue("@SoHD", SoHD1);
                       // cmd.Parameters.AddWithValue("@Checked", "0");
                        SqlParameter code = new SqlParameter("@MaCT", SqlDbType.Int);
                        code.Direction = ParameterDirection.Output;
                        cmd.Parameters.Add(code);
                        SqlDataReader sdr = cmd.ExecuteReader();
                        ChungTu1 = cmd.Parameters["@MaCT"].Value.ToString();
                        sdr.Close();
                        cmd.Parameters.Clear();
                    }
                    if (txt_SoCT.Enabled == true)
                    {
                        if (txt_SoCT.Text == "")
                            MessageBox.Show("Bạn chưa nhập số chứng từ");
                        else
                            ChungTu1 = txt_SoCT.Text.Trim();
                    }
                    if (ChungTu1 != "0")
                    {
                        cmd.CommandText = "Ins_KTPXK";
                        for (i = dataGridView3.Rows.Count - 2; i >= 0; i--)
                        {
                            MaSP1 = dataGridView3.Rows[i].Cells["MaSPoutput"].Value.ToString();
                            ArticleNumber1 = dataGridView3.Rows[i].Cells["ArticleNumberoutput"].Value.ToString();
                            IDNumber1 = dataGridView3.Rows[i].Cells["IDNumberoutput"].Value.ToString();
                            //SoHD1 = dataGridView3.Rows[i].Cells["SoHDoutput"].Value.ToString();
                            KhachHang1 = dataGridView3.Rows[i].Cells["KhachHangoutput"].Value.ToString();
                            LoaiGo1 = dataGridView3.Rows[i].Cells["LoaiGooutput"].Value.ToString();
                            DVGC1 = dataGridView3.Rows[i].Cells["DVGCoutput"].Value.ToString();
                            //SoBB1 = dataGridView3.Rows[i].Cells["SoBBoutput"].Value.ToString();
                            SLXuat_d = double.Parse(dataGridView3.Rows[i].Cells["SLoutput"].Value.ToString());
                            SoThung1 = dataGridView3.Rows[i].Cells["SLThungoutput"].Value.ToString();
                            DVT1 = dataGridView3.Rows[i].Cells["DVToutput"].Value.ToString();
                            Ngay1 = dataGridView3.Rows[i].Cells["NgayInsertoutput"].Value.ToString();
                            LyDo1 = dataGridView3.Rows[i].Cells["LyDooutput"].Value.ToString();
                            GhiChu1 = dataGridView3.Rows[i].Cells["GhiChuoutput"].Value.ToString();
                            ViTri1 = dataGridView3.Rows[i].Cells["ViTrioutput"].Value.ToString();
                            cmd.Parameters.AddWithValue("@ChungTu", ChungTu1);
                            cmd.Parameters.AddWithValue("@MaSP", MaSP1);
                            cmd.Parameters.AddWithValue("@IDNumber", IDNumber1);
                            cmd.Parameters.AddWithValue("@ArticleNumber", ArticleNumber1);
                            cmd.Parameters.AddWithValue("@SoHD", "");
                            cmd.Parameters.AddWithValue("@KhachHang", KhachHang1);
                            cmd.Parameters.AddWithValue("@LoaiGo", LoaiGo1);
                            cmd.Parameters.AddWithValue("@DVGC", DVGC1);
                            cmd.Parameters.AddWithValue("@SoBB", "");
                            cmd.Parameters.AddWithValue("@SLXuat", SLXuat_d);
                            cmd.Parameters.AddWithValue("@SLThungXuat", SoThung1);
                            cmd.Parameters.AddWithValue("@DVT", DVT1);
                            cmd.Parameters.AddWithValue("@Ngay", Ngay1);
                            cmd.Parameters.AddWithValue("@ViTri", ViTri1);
                            cmd.Parameters.AddWithValue("@UserNhap", UserNhap);
                            cmd.Parameters.AddWithValue("@GhiChu", GhiChu1);
                            cmd.Parameters.AddWithValue("@LyDo", LyDo1);
                            cmd.ExecuteNonQuery();
                            cmd.Parameters.Clear();
                            dataGridView3.Rows.RemoveAt(i);
                        }
                        lb_TongXuat.Text = "0";
                        txt_SoBBoutput.Text = "";
                        txt_SLoutput.Text = "";
                        txt_SLThungoutput.Text = "";
                        txt_GhiChuoutput.Text = "";
                        cb_DVGCoutput.Text = "";
                        cb_LoaiGooutput.Text = "";
                        lb_TonKho.Text = "0";
                        lb_Chungtu.Text = ChungTu1;
                        txt_ArticleNumberoutput.Text = "";
                        txt_IDNumberoutput.Text = "";
                        MessageBox.Show("Dữ Liệu được lưu thành công");
                        bt_saveoutput.Enabled = false;
                       
                    }
                }
                else
                {
                    MessageBox.Show("Đã xảy ra lỗi. Kiểm tra lại thông tin nhập");
                }
            }
            catch (Exception ex)
            {
                string s = "insert duplicate key";
                string FK = "FOREIGN KEY constraint";
                string s1 = ex.Message.ToString();
                if (s1.Contains(s))
                { MessageBox.Show("Insert không thành công \n" + "Mã đã tồn tại "); }
                else if (s1.Contains(FK))
                { MessageBox.Show("Nhập sai thông tin trong Combobox");
                //MessageBox.Show(ex.Message);
                }
                else
                    MessageBox.Show(ex.Message);
                MessageBox.Show("Đã xảy ra lỗi khi thêm dữ liệu, vui lòng kiểm tra lại");
                if (txt_SoCT.Enabled == false)
                {
                    string Serial1 = "select Serial,ChungTu,ViTri from dbo.KhoTP_XK where ChungTu=" + ChungTu1;
                    DataSet ds1 = dta.dts(Serial1);

                    cmd.Parameters.Clear();
                    if (ds1.Tables[0].Rows.Count > 0)
                    {
                        cmd.CommandText = "Tran_Del_Up_XKTP";
                        for (j = 0; j < ds1.Tables[0].Rows.Count; j++)
                        {
                            Serial1 = ds1.Tables[0].Rows[j]["Serial"].ToString();
                           
                            ViTri1 = ds1.Tables[0].Rows[j]["ViTri"].ToString();
                            cmd.Parameters.AddWithValue("@Serial", Serial1);
                            cmd.Parameters.AddWithValue("@ViTri", ViTri1);
                            
                            cmd.ExecuteNonQuery();
                            cmd.Parameters.Clear();
                        }
                        ds1.Clear();
                        dataGridView3.Rows.RemoveAt(dataGridView3.Rows.Count-2);
                    }
                    MessageBox.Show("Chứng Từ xảy ra lỗi vừa rồi đã được xóa");
                }
     
            }
            finally
            {
                Conn.Close();
                cmd.Dispose();
                bt_addproduct.Enabled = false;
                txt_SoCT.Enabled = false;
                txt_SoCT.Text = "";
            }
        }

        private void bt_saveoutput_Click(object sender, EventArgs e)
        {
            save_output();
        }

        private void bt_editoutput_Click(object sender, EventArgs e)
        {
            try
            {
                string datecheck;
                int date_count;
                Process prs = new Process();
                SqlConnection Conn = prs.Connect();
                SqlCommand cmd = new SqlCommand();
                DialogResult d = MessageBox.Show("Bạn có chắc muốn sửa Thông Tin có Số Serial " + lb_serialoutput.Text, "Thông Báo", MessageBoxButtons.OKCancel);
                MaSP1 = prs.substring_right(cb_MaSPoutput.Text, child);
                SoHD1 = txt_SoHDoutput.Text;
                KhachHang1 = cb_KhachHangoutput.Text;
                LoaiGo1 = cb_LoaiGooutput.Text;
                DVGC1 = cb_DVGCoutput.Text;
                SoBB1 = txt_SoBBoutput.Text;
               
                GhiChu1 = txt_GhiChuoutput.Text;
                LyDo1 = prs.substring_right(cb_LyDoXuat.Text, child);
                if (LyDo1 == "")
                    LyDo1 = cb_LyDoXuat.Text; 
               SoThung_d = double.Parse(txt_SLThungoutput.Text);
               
                SLXuat_d = double.Parse(txt_SLoutput.Text);
                DVT1 = cb_DVToutput.Text;
                Ngay1 = txt_Ngayoutput.Text;
                string[] temp = Ngay1.Split('/');
                Ngay1 = temp[1] + "/" + temp[0] + "/" + temp[2];
                Conn.Open();
                cmd.Connection = Conn;
                datecheck = @"select datediff(dd,NgayInsert,getdate()) from dbo.KhoTP_XK where Serial='" + lb_serialoutput.Text + "'";
               
                if (d == DialogResult.OK)
                {
                    cmd.CommandText = datecheck;
                    date_count = int.Parse(cmd.ExecuteScalar().ToString());
                    if (date_count <= 1 || lb_user.Text == "administrator")
                    {
                        cmd.CommandText = "Upd_KTPXK";
                        cmd.CommandType = CommandType.StoredProcedure;
                        cmd.Parameters.AddWithValue("@MaSP", MaSP1);
                        cmd.Parameters.AddWithValue("@SoHD", SoHD1);
                        cmd.Parameters.AddWithValue("@KhachHang", KhachHang1);
                        cmd.Parameters.AddWithValue("@LoaiGo", LoaiGo1);
                        cmd.Parameters.AddWithValue("@DVGC", DVGC1);
                        cmd.Parameters.AddWithValue("@SoBB", SoBB1);
                       
                        cmd.Parameters.AddWithValue("@SLXuat", SLXuat_d);
                        cmd.Parameters.AddWithValue("@SLThungXuat",SoThung_d);
                        cmd.Parameters.AddWithValue("@DVT", DVT1);
                        cmd.Parameters.AddWithValue("@Ngay", Ngay1);
                        cmd.Parameters.AddWithValue("@Useredit", lb_user.Text);
                        cmd.Parameters.AddWithValue("@GhiChu", GhiChu1);
                        cmd.Parameters.AddWithValue("@LyDo", LyDo1);
                        cmd.Parameters.AddWithValue("@Serial", lb_serialoutput.Text);
                        cmd.ExecuteNonQuery();
                       
                        MessageBox.Show("Chỉnh Sửa Thành Công");
                        bt_resetoutput_Click(null, null);
                    }
                    else
                        MessageBox.Show("Không được phép chỉnh sửa");
                    Conn.Close();
                    cmd.Dispose();
                    for (int i = 0; i < dataGridView2.Rows.Count - 1; i++)
                    {
                        dataGridView4.Rows.RemoveAt(0);
                    }
                    prs.reset_txt(groupPanel3);
                    bt_editoutput.Enabled = false;
                    bt_deleteoutput.Enabled = false;
                    lb_serialoutput.Text = "0";
                    lb_TonKho.Text = "0";
                }
            }
            catch (Exception ex)
            {
                string s = "The conversion of a char data type to a datetime";
                string s1 = ex.Message.ToString();
                if (s1.Contains(s))
                { MessageBox.Show("Ngày Tháng Nhập chưa đúng"); }
                MessageBox.Show(ex.Message);
            }

        }
        private void Display_output(int i)
        {
            try
            {
                MaSP1 = dataGridView4.Rows[i].Cells["MaSP"].Value.ToString();
                TenSP1 = dataGridView4.Rows[i].Cells["TenSP"].Value.ToString();
              
                cb_MaSPoutput.Text = TenSP1 + " - " + MaSP1;
                //cb_MaCTinput.Text = TenCT1 + " - " + MaCT1;
                txt_SoHDoutput.Text = dataGridView4.Rows[i].Cells["SoHD"].Value.ToString();
                cb_KhachHangoutput.Text = dataGridView4.Rows[i].Cells["KhachHang"].Value.ToString();
                cb_LoaiGooutput.Text = dataGridView4.Rows[i].Cells["LoaiGo"].Value.ToString();
                cb_DVGCoutput.Text = dataGridView4.Rows[i].Cells["DVGC"].Value.ToString();
                txt_SoBBoutput.Text = dataGridView4.Rows[i].Cells["SoBB"].Value.ToString();
                txt_SLoutput.Text = dataGridView4.Rows[i].Cells["SLXuat"].Value.ToString();
                txt_SLThungoutput.Text = dataGridView4.Rows[i].Cells["SLThungXuat"].Value.ToString();
                cb_DVToutput.Text = dataGridView4.Rows[i].Cells["DVT"].Value.ToString();
               // txt_SoThunginput.Text = dataGridView4.Rows[i].Cells["SLThungNhap"].Value.ToString();
                txt_Ngayoutput.Text = dataGridView4.Rows[i].Cells["Ngay"].Value.ToString();
                lb_serialoutput.Text = dataGridView4.Rows[i].Cells["Serial"].Value.ToString();
                txt_GhiChuoutput.Text = dataGridView4.Rows[i].Cells["GhiChu"].Value.ToString();
                cb_LyDoXuat.Text = dataGridView4.Rows[i].Cells["LyDo"].Value.ToString();
                cb_ViTrioutput.Text = dataGridView4.Rows[i].Cells["ViTri"].Value.ToString();
                txt_IDNumberoutput.Text = dataGridView4.Rows[i].Cells["IDNumber"].Value.ToString();
                txt_ArticleNumberoutput.Text = dataGridView4.Rows[i].Cells["ArticleNumber"].Value.ToString();
                txt_SoCT.Text = dataGridView4.Rows[i].Cells["ChungTu"].Value.ToString();
                cb_ViTrioutput.Enabled = false;
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }
        private void search_Output()
        {
            try
            {
                string search = null;
                Process prs = new Process();
                DataSet ds = new DataSet();
                if (txt_IDNumberoutput.Text == "")
                {
                    if (cb_MaSPoutput.Text != "" && txt_Ngayoutput.Text != "")
                    {
                        MaSP1 = prs.substring_right(cb_MaSPoutput.Text, child);
                        string[] temp = txt_Ngayoutput.Text.Split('/');
                        Ngay1 = temp[1] + "/" + temp[0] + "/" + temp[2];
                    }
                    if (MaSP1 == "")
                        MessageBox.Show("Mã SP không chính xác");
                    else
                    {
                        search = @"select dbo.KhoTP_XK.*,dbo.Load_cbSP.TenSP from dbo.KhoTP_XK inner join dbo.Load_cbSP on KhoTP_XK.MaSP=dbo.Load_cbSP.MaSP
                                where SLXuat>0 and Ngay='" + Ngay1 + "'and dbo.Load_cbSP.MaSP='" + MaSP1 + "'";
                    }
                }
                else
                {
                    IDNumber1 = txt_IDNumberoutput.Text.Trim();
                    search = @"select dbo.KhoTP_XK.*,dbo.Load_cbSP.TenSP from dbo.KhoTP_XK inner join dbo.Load_cbSP on KhoTP_XK.MaSP=dbo.Load_cbSP.MaSP
                                where SLXuat>0 and IDNumber='"+IDNumber1+"'";
                }
                //MessageBox.Show(search);
                ds = prs.dts(search);
                if (ds.Tables[0].Rows.Count == 0)
                    MessageBox.Show("Không có dữ liệu, vui lòng kiểm tra lại thông tin tìm kiếm");
                else
                {
                    dataGridView4.DataSource = ds.Tables[0];
                    int k = dataGridView4.Rows.Count - 2;
                    Display_output(k);
                    lb_indexout.Text = k.ToString();
                    bt_editoutput.Enabled = true;
                    bt_deleteoutput.Enabled = true;
                    bt_insertoutput.Enabled = false;
                    txt_ArticleNumberoutput.Enabled = false;
                    txt_IDNumberoutput.Enabled = false;
                    txt_SoCT.Enabled = false;
                    lb_CT.Visible = true;
                   
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }

        private void bt_searchoutput_Click(object sender, EventArgs e)
        {
            search_Output();
        }

        private void bt_prevoutput_Click(object sender, EventArgs e)
        {
            try
            {
                if (dataGridView4.Rows.Count > 1)
                {
                    int i;
                    i = int.Parse(lb_indexout.Text);
                    if (i > 0)
                    {
                        i--;
                        Display_output(i);
                        lb_indexout.Text = i.ToString();
                    }
                }
            }
            catch (Exception ex)
            { MessageBox.Show(ex.Message); }
        }

        private void bt_nextoutput_Click(object sender, EventArgs e)
        {
            try
            {
                if (dataGridView4.Rows.Count > 1)
                {
                    int i;
                    i = int.Parse(lb_indexout.Text);
                    if (i < dataGridView4.Rows.Count - 2)
                    {
                        i++;
                        Display_output(i);
                        lb_indexout.Text = i.ToString();
                    }
                }
            }
            catch (Exception ex)
            { MessageBox.Show(ex.Message); }
        }

        private void bt_deleteoutput_Click(object sender, EventArgs e)
        {
            Data dta = new Data();
            SqlConnection Conn = dta.Connect();
            Conn.Open();
            SqlCommand cmd = new SqlCommand();
            cmd.Connection = Conn;
            DialogResult d = MessageBox.Show("Bạn có chắc muốn xóa Thông Tin có Số Serial " + lb_serialoutput.Text, "Thông Báo", MessageBoxButtons.OKCancel);
            if (d == DialogResult.OK)
            {
                try
                {
                    string datecheck = @"select datediff(dd,NgayInsert,getdate()) from dbo.KhoTP_XK where Serial='" + lb_serialoutput.Text + "'";
                    // string delete = @"delete from dbo.KhoTP_XK where Serial='" + lb_serialoutput.Text + "'";
                   

                    cmd.CommandText = datecheck;
                    int date_count = int.Parse(cmd.ExecuteScalar().ToString());
                    if (date_count <= 1 || lb_user.Text == "administrator")
                    {
                        cmd.CommandType = CommandType.StoredProcedure;
                        cmd.CommandText = "Tran_Del_Up_XKTP";
                        cmd.Parameters.AddWithValue("@Serial", lb_serialoutput.Text);
                        cmd.Parameters.AddWithValue("@ViTri", cb_ViTrioutput.Text);


                        cmd.ExecuteNonQuery();
                        MessageBox.Show("Dữ liệu được xóa thành công");
                        lb_serialoutput.Text = "0";
                        txt_SoCT.Enabled = false;
                        lb_CT.Visible = false;
                        txt_SoCT.Text = "";
                        cb_LyDoXuat.Text = "XUAT BAN - TPXB";
                    }
                    else
                    {
                        MessageBox.Show("Quá thời gian cho phép, Không được phép xóa");
                    }
                    Conn.Close();
                    cmd.Dispose();
                    for (i = dataGridView4.Rows.Count - 2; i >= 0; i--)
                    {
                        dataGridView4.Rows.RemoveAt(i);
                    }
                    dta.reset_txt(groupPanel3);
                    bt_deleteoutput.Enabled = false;
                    bt_editoutput.Enabled = false;

                }
                catch (Exception ex)
                {
                    MessageBox.Show(ex.Message);
                }
                finally
                {
                    Conn.Close();
                    cmd.Dispose();
                }
            }
        }

       
        private void TonKho()
        {
            Process prs = new Process();
            SqlConnection Conn = prs.Connect();
            SqlCommand cmd = new SqlCommand();
            try
            {
                Conn.Open();
                cmd.Connection = Conn;
                MaSP1 = prs.substring_right(cb_MaSPoutput.Text, child);
                string TonKho = @"select TonKho from dbo.KhoTP_TK where MaSP='" + MaSP1 + "' and LoaiGo='"+cb_LoaiGooutput.Text+"'";
                cmd.CommandText = TonKho;
                lb_TonKho.Text = cmd.ExecuteScalar().ToString();
            }
            catch
            {
                //MessageBox.Show(ex.Message);
                lb_TonKho.Text = "0";
            }
            finally
            {
                Conn.Close();
                cmd.Dispose();
            }

        }

        private void cb_MaSPoutput_SelectedIndexChanged(object sender, EventArgs e)
        {
            //TonKho();
        }
        private void check_TonKho()
        {
            SLXuat_d = double.Parse(txt_SLoutput.Text);
            TK_KTP = double.Parse(lb_TonKho.Text);
            if (SLXuat_d > TK_KTP)
            {
                MessageBox.Show("SL xuất không vượt quá SL Tồn Kho");
                txt_SLoutput.Text = "";
            }
        }

        private void txt_SLoutput_TextChanged(object sender, EventArgs e)
        {
           
                FormProcess Frp = new FormProcess();
                Frp.checktext_number(txt_SLoutput);
        }
        private void search_TK()
        {
            Process prs = new Process();
            string search = null;
            try
            {
                if (cb_MaSPTK.Text == "")
                {
                    search = @"select dbo.Load_cbSP.MaSP,dbo.Load_cbSP.TenSP,dbo.KhoTP_TK.TonKho,SLThung from dbo.KhoTP_TK inner join dbo.Load_cbSP on dbo.KhoTP_TK.MaSP=dbo.Load_cbSP.MaSP";
                }
                else
                {
                    MaSP1 = prs.substring_right(cb_MaSPTK.Text, child);
                    if (MaSP1 != "")
                        search = @"select dbo.Load_cbSP.MaSP,dbo.Load_cbSP.TenSP,dbo.KhoTP_TK.TonKho,SLThung from dbo.KhoTP_TK inner join dbo.Load_cbSP on dbo.KhoTP_TK.MaSP=dbo.Load_cbSP.MaSP where dbo.Load_cbSP.MaSP='" + MaSP1 + "'";
                    else
                        MessageBox.Show("Kiểm tra lại thông tin tìm kiếm");
                }
                DataSet ds = prs.dts(search);
                if (ds.Tables[0].Rows.Count > 0)
                {
                    if (dataGridView5.Rows.Count > 1)
                        dataGridView5.Rows.Clear();
                    for (i = 0; i < ds.Tables[0].Rows.Count; i++)
                    {
                        MaSP1 = ds.Tables[0].Rows[i]["MaSP"].ToString();
                        TenSP1 = ds.Tables[0].Rows[i]["TenSP"].ToString();

                        SLNhap_d = double.Parse(ds.Tables[0].Rows[i]["TonKho"].ToString());
                        SLNhap1 = string.Format("{0:###,###,###}", SLNhap_d);
                        SoThung1 = ds.Tables[0].Rows[i]["SLThung"].ToString();
                        dataGridView5.Rows.Add(MaSP1, TenSP1, SLNhap1,SoThung1);
                    }
                    prs.formatcolordatagrid(dataGridView5);
                    ds.Clear();
                }

                else
                    MessageBox.Show("Không có dữ liệu. Vui lòng kiểm tra lại thông tin tìm kiếm");
            }
            catch(Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }

        private void bt_searchTK_Click(object sender, EventArgs e)
        {
            search_TK();
        }
        private void report_NKTP()
        {
            try
            {
                if (txt_Ngayinput.Text != "")
                {
                    Process prs = new Process();
                    Ngay1 = txt_Ngayinput.Text;
                    string[] temp = Ngay1.Split('/');
                    Ngay1 = temp[1] + "/" + temp[0] + "/" + temp[2];
                    string print_NKTP = @"select qry1.MaSP,SanPham.TenSP,qry1.SoHD as HDNgay,qry1.KhachHang as TenKH,qry1.LoaiGo,qry1.DVGC as DVT,qry1.SoBB,qry1.SLNhap,qry1.SLThungNhap as DBNhap,qry1.Ngay,qry1.Serial as Serial_NK,dbo.LyDo.LyDo as LyDoNhap from
                    (select MaSP, SoHD, KhachHang, LoaiGo, DVGC, SoBB, SLNhap, SLThungNhap,Ngay, Serial,LyDo from dbo.KhoTP where Ngay>='" + Ngay1 + " 00:00:00' and Ngay<='" + Ngay1 + " 23:59:59' and SLNhap is not null) as qry1 inner join dbo.SanPham on qry1.MaSP=dbo.SanPham.MaSP inner join dbo.LyDo on dbo.LyDo.MaLyDo=qry1.LyDo order by qry1.MaSP";
                    DataSet ds = prs.dts(print_NKTP);
                    Fr_Report FrR = new Fr_Report();
                    Ngay1 = txt_Ngayinput.Text;
                    FrR.report_NKTP(ds, Ngay1);
                    FrR.Show();
                    ds.Clear();

                }
                else
                    MessageBox.Show("Chọn ngày cần in");
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }

        private void bt_printinput_Click(object sender, EventArgs e)
        {
            print_Nhap();
        }

        private void txt_SLThungoutput_TextChanged(object sender, EventArgs e)
        {
            checktext_number(txt_SLThungoutput);
        }
       

        private void bt_printoutput_Click(object sender, EventArgs e)
        {
            print_Xuat();
        }

        private void report_TH()
        {
            try
            {
                
                Process prs = new Process();
                int year = 0;
                SqlConnection Conn = prs.Connect();
                Conn.Open();
                SqlCommand cmd = new SqlCommand();
                cmd.CommandType = CommandType.StoredProcedure;
                SqlCommand cmd1 = new SqlCommand();
                DataSet ds=new DataSet();
                GhiChu1="Các số lượng nhập xuất trong báo cáo đã trừ số lượng lập phiếu";
                cmd.Connection = Conn;
                cmd1.Connection = Conn;
                if (cb_MaSPReport.Text == "")
                {
                    cmd.Parameters.AddWithValue("@check", "0");
                    cmd.Parameters.AddWithValue("@MaSP", "0");
                }
                else
                {
                    MaSP1 = prs.substring_right(cb_MaSPReport.Text, child);
                    if (MaSP1 == "")
                        MessageBox.Show("Nhập sai thông tin sản phẩm");
                    else
                    {
                        cmd.Parameters.AddWithValue("@check", "1");
                        cmd.Parameters.AddWithValue("@MaSP", MaSP1);
                    }
                }
                
                if (rd_NhapXuatNgay.Checked == true)
                {
                    string[] temp = txt_NgayBegin.Text.Split('/');
                    Ngay_start1 = temp[1] + "/" + temp[0] + "/" + temp[2];
                    string[] temp2 = txt_NgayEnd.Text.Split('/');
                    Ngay_End1 = temp2[1] + "/" + temp2[0] + "/" + temp2[2];
                    cmd.Parameters.AddWithValue("@datebegin", Ngay_start1);
                    cmd.Parameters.AddWithValue("@dateend", Ngay_End1);     
                    cmd.CommandText = "prc_KTP_TH_Ngay";
                    Ngay_start1 = "Ngày " + txt_NgayBegin.Text;
                    Ngay_End1 = " - " + txt_NgayEnd.Text;
                }
                if (rd_NhapXuatTuan.Checked == true)
                {
                    if (txt_Nam.Text == "")
                        MessageBox.Show("Bạn cần nhập năm tìm kiếm (yyyy)");
                    else
                    {
                        int Tuan_begin = int.Parse(txt_NgayBegin.Text);        
                        int Tuan_end = int.Parse(txt_NgayEnd.Text);   
                        year = int.Parse(txt_Nam.Text);
                        Tuan_begin = 40908 + (year - 2012) * 52 * 7 + (Tuan_begin - 1) * 7; //40908 tính từ năm 1900 đến năm 2012
                        Tuan_end = 40908 + (year - 2012) * 52 * 7 + (Tuan_end - 1) * 7 + 7; //tăng lên 1 ngày để so sánh <
                        cmd1.CommandText = "select qry1.NgayStart,qry2.NgayEnd from (select ID=1,convert(varchar(10),CAST("+Tuan_begin+" as datetime),101) as NgayStart) as qry1 inner join (select ID=1,convert(varchar(10),CAST("+Tuan_end+" as datetime),101) as NgayEnd ) as qry2 on qry1.ID=qry2.ID";
                        SqlDataReader rd = cmd1.ExecuteReader();
                           
                        while (rd.Read())
                        {
                            Ngay_start1 = rd["NgayStart"].ToString()+" 00:00:00";
                            Ngay_End1 = rd["NgayEnd"].ToString()+" 00:00:00";
                        }
                        MessageBox.Show(Ngay_start1+" "+Ngay_End1);
                        cmd.Parameters.AddWithValue("@datebegin", Ngay_start1);
                        cmd.Parameters.AddWithValue("@dateend", Ngay_End1);
                           
                        cmd.CommandText = "prc_KTP_TH_Tuan";
                        /*report = @"select dbo.Load_cbSP.TenSP,qry2.SLNhap,qry2.DBNhap,qry2.SLXuat,qry2.DBXuat,qry2.TonDau,qry2.DBTonDau,qry2.SLNhap-qry2.SLXuat as TonPS,qry2.DBNhap-qry2.DBXuat as DBPS,qry2.TonDau+qry2.SLNhap-qry2.SLXuat as SLTon,qry2.DBTonDau+qry2.DBNhap-qry2.DBXuat as DBTonCuoi,(qry2.TonDau+qry2.SLNhap-qry2.SLXuat)/dbo.Load_cbSP.Cont as SoLuong,qry2.Ngay,LyDo.LyDo as LyDoNhap
                                    from(select MaSP,sum(SLNhap) as SLNhap,sum(DBNhap) as DBNhap,sum(SLXuat) as SLXuat,sum(DBXuat) as DBXuat,sum(TonDau) as TonDau,sum(DBTonDau) as DBTonDau,Ngay1 as Ngay,LyDo
                                    from ((select MaSP,sum(isnull(SLNhap,0)) as SLNhap,sum(isnull(SLXuat,0)) as SLXuat, sum(isnull(SLThungNhap,0)) as DBNhap,sum(isnull(SLThungXuat,0)) as DBXuat,TonDau=0,DBTonDau=0,convert(char(2),datepart(wk,Ngay))as Ngay1,LyDo from dbo.KhoTP
                                    where datepart(wk,Ngay)>="+Ngay_start1+" and datepart(wk,Ngay)<="+Ngay_End1+" and datepart(yy,Ngay)="+year+" Group by MaSP,datepart(wk,Ngay),LyDo) union all (select MaSP,SLNhap=0,SLXuat=0,DBNhap=0,DBXuat=0,sum(isnull(SLNhap,0))-sum(isnull(SLXuat,0)) as TonDau,sum(isnull(SLThungNhap,0))-sum(isnull(SLThungXuat,0)) as DBTonDau,Ngay1=N'Tồn Đầu',LyDo from dbo.KhoTP where Ngay<(select cast("+Tuan_int+" as datetime)) group by MaSP,Ngay,LyDo)) as qry1 group by MaSP,Ngay1,LyDo) as qry2 inner join dbo.Load_cbSP on qry2.MaSP=dbo.Load_cbSP.MaSP inner join dbo.LyDo on LyDo.MaLyDo=qry2.LyDo";*/
                        Ngay_start1 = "Tuần "+txt_NgayBegin.Text;
                        Ngay_End1 = " - " + txt_NgayEnd.Text;
                    }
                }
                if (rd_NhapXuatThang.Checked == true)
                {
                    if (txt_Nam.Text == "")
                        MessageBox.Show("Bạn cần nhập năm tìm kiếm (yyyy)");
                    else
                    {
                        string Thang_begin = int.Parse(txt_NgayBegin.Text).ToString();
                        string Thang_end = int.Parse(txt_NgayEnd.Text).ToString();
                        year = int.Parse(txt_Nam.Text);
                        Ngay_start1 = Thang_begin+"/01/"+ year.ToString()+" 00:00:00";
                        if(Thang_end=="1"||Thang_end=="3"||Thang_end=="5"||Thang_end=="7"||Thang_end=="8"||Thang_end=="10"||Thang_end=="12")
                            Ngay_End1 =Thang_end+"/31/"+year.ToString()+" 23:59:59";
                        if (Thang_end == "4" || Thang_end == "6" || Thang_end == "9" || Thang_end == "11")
                            Ngay_End1 = Thang_end+"/30/"+ year.ToString() + " 23:59:59";
                        if (Thang_end == "2" && year % 4 == 0)
                            Ngay_End1 = Thang_end+"/28/" +year.ToString() + " 23:59:59";
                        if(Thang_end=="2"&&year%4!=0)
                            Ngay_End1 = Thang_end+"/29/"+ year.ToString() + " 23:59:59";
                        //MessageBox.Show(Ngay_start1 + " " + Ngay_End1);
                        cmd.Parameters.AddWithValue("@datebegin", Ngay_start1);
                        cmd.Parameters.AddWithValue("@dateend", Ngay_End1);

                        cmd.CommandText = "prc_KTP_TH_Thang";
                        /*report = @"select dbo.Load_cbSP.TenSP,qry2.SLNhap,qry2.DBNhap,qry2.SLXuat,qry2.DBXuat,qry2.TonDau,qry2.DBTonDau,qry2.SLNhap-qry2.SLXuat as TonPS,qry2.DBNhap-qry2.DBXuat as DBPS,qry2.TonDau+qry2.SLNhap-qry2.SLXuat as SLTon,qry2.DBTonDau+qry2.DBNhap-qry2.DBXuat as DBTonCuoi,(qry2.TonDau+qry2.SLNhap-qry2.SLXuat)/dbo.Load_cbSP.Cont as SoLuong,qry2.Ngay,LyDo.LyDo as LyDoNhap
                                    from(select MaSP,sum(SLNhap) as SLNhap,sum(DBNhap) as DBNhap,sum(SLXuat) as SLXuat,sum(DBXuat) as DBXuat,sum(TonDau) as TonDau,sum(DBTonDau) as DBTonDau,Ngay1 as Ngay,LyDo
                                    from ((select MaSP,sum(isnull(SLNhap,0)) as SLNhap,sum(isnull(SLXuat,0)) as SLXuat, sum(isnull(SLThungNhap,0)) as DBNhap,sum(isnull(SLThungXuat,0)) as DBXuat,TonDau=0,DBTonDau=0,convert(char(2),datepart(wk,Ngay))as Ngay1,LyDo from dbo.KhoTP
                                    where datepart(wk,Ngay)>="+Ngay_start1+" and datepart(wk,Ngay)<="+Ngay_End1+" and datepart(yy,Ngay)="+year+" Group by MaSP,datepart(wk,Ngay),LyDo) union all (select MaSP,SLNhap=0,SLXuat=0,DBNhap=0,DBXuat=0,sum(isnull(SLNhap,0))-sum(isnull(SLXuat,0)) as TonDau,sum(isnull(SLThungNhap,0))-sum(isnull(SLThungXuat,0)) as DBTonDau,Ngay1=N'Tồn Đầu',LyDo from dbo.KhoTP where Ngay<(select cast("+Tuan_int+" as datetime)) group by MaSP,Ngay,LyDo)) as qry1 group by MaSP,Ngay1,LyDo) as qry2 inner join dbo.Load_cbSP on qry2.MaSP=dbo.Load_cbSP.MaSP inner join dbo.LyDo on LyDo.MaLyDo=qry2.LyDo";*/
                        Ngay_start1 = "Tháng " + txt_NgayBegin.Text;
                        Ngay_End1 = " - " + txt_NgayEnd.Text;
                    }
                }
                if (rd_ThucXuat.Checked == true)
                {
                    MessageBox.Show("Dạng báo cáo này không xuất theo thời gian");
                    txt_NgayBegin.Text = "";
                    txt_NgayEnd.Text = "";
                    string_temp = @"SELECT  MaSP,[TenSP],[LoaiGo],[SLNhap],[DBNhap],[SLXuat],[DBXuat],[SLChuaXuat] as SoLuong,[SLThungChuaXuat] as DBPS,[SLNhap]-[SLXuat] as SLTon,[DBNhap]-[DBXuat] as DBTonCuoi,[SLNhap]-[SLXuat]-[SLChuaXuat] as TonPS,[DBNhap]-[DBXuat]-[SLThungChuaXuat] as DBTonPS
                    FROM [dbo].[KhoTP_TKPhieu]";
                    if (cb_MaSPReport.Text != "")
                        string_temp += " where MaSP='" + MaSP1;

                }
                if (rd_LyDoNhap.Checked == true)
                {
                    if (chk_NhaptheoTG.Checked == false)
                    {
                       // MessageBox.Show("File");
                        txt_NgayBegin.Text = "";
                        txt_NgayEnd.Text = "";
                        string_temp = @"select qry1.MaSP,dbo.Load_cbSP.TenSP,dbo.LyDo.LyDo as LyDoNhap,qry1.LoaiGo,sum(qry1.SLNhap) as SLNhap,sum(qry1.SLThungNhap) as DBNhap,sum(qry1.SLXuat) as SLXuat,sum(qry1.SLThungXuat) as DBXuat,sum(qry1.SLNhap-qry1.SLXuat) as SLTon,sum(qry1.SLThungNhap-qry1.SLThungXuat) as DBTonCuoi
                                        from
                                        (SELECT [KhoTP_NK].[MaSP],[KhoTP_NK].[IDNumber],[KhoTP_NK].[LoaiGo],[KhoTP_NK].[SLNhap],[KhoTP_NK].[SLThungNhap],isnull([KhoTP_XK].SLXuat,0) as SLXuat,isnull(SLThungXuat,0) as SLThungXuat,[KhoTP_XK].[Ngay],[KhoTP_NK].[LyDo]
                                            FROM [dbo].[KhoTP_NK] left join [KhoTP_XK] on KhoTP_NK.IDNumber=KhoTP_XK.IDNumber) as qry1 inner join dbo.Load_cbSP on dbo.Load_cbSP.MaSP=qry1.MaSP left join dbo.LyDo on dbo.LyDo.MaLyDo=qry1.LyDo
                                            group by  qry1.MaSP,dbo.Load_cbSP.TenSP,dbo.LyDo.LyDo,qry1.LoaiGo";
                        GhiChu1 = "Lý do được xác định theo lý do nhập";
                        if (cb_MaSPReport.Text != "")
                            string_temp += " where MaSP='" + MaSP1;
                    }
                    if (chk_NhaptheoTG.Checked == true)
                    {
                        if (txt_NgayBegin.Text != "" && txt_NgayEnd.Text != "")
                        {
                            string[] temp = txt_NgayBegin.Text.Split('/');
                            Ngay_start1 = temp[1] + "/" + temp[0] + "/" + temp[2];
                            string[] temp2 = txt_NgayEnd.Text.Split('/');
                            Ngay_End1 = temp2[1] + "/" + temp2[0] + "/" + temp2[2];
                            string_temp = @"select qry1.MaSP,dbo.Load_cbSP.TenSP,dbo.LyDo.LyDo as LyDoNhap,qry1.SLNhap,qry1.DBNhap
                                                from
                                                (SELECT [KhoTP_NK].[MaSP],sum([KhoTP_NK].[SLNhap]) as SLNhap,sum([KhoTP_NK].[SLThungNhap]) as DBNhap,[KhoTP_NK].[LyDo]
                                                FROM [dbo].[KhoTP_NK] where Ngay>='" + Ngay_start1 + "' and Ngay<='" + Ngay_End1 + "' group by [KhoTP_NK].[LyDo],MaSP) as qry1 inner join dbo.Load_cbSP on Load_cbSP.MaSP=qry1.MaSP left join LyDo on LyDo.MaLyDo=qry1.LyDo";
                            GhiChu1 = "Lý do được xác định theo lý do nhập từ ngày: " + txt_NgayBegin.Text + " đến " + txt_NgayEnd.Text;
                        }
                        else
                        {
                            MessageBox.Show("Nhập đầy đủ ngày tháng");
                            string_temp = "";
                        }
                    }
                }
                if (rd_LyDoXuat.Checked == true)
                {
                    if (chk_XuattheoTG.Checked == false)
                    {
                        MessageBox.Show("Dạng báo cáo này không hỗ trợ xuất theo thời gian");
                        txt_NgayBegin.Text = "";
                        txt_NgayEnd.Text = "";
                        string_temp = @"select qry1.MaSP,dbo.Load_cbSP.TenSP,dbo.LyDo.LyDo as LyDoNhap,qry1.LoaiGo,sum(qry1.SLNhap) as SLNhap,sum(qry1.SLThungNhap) as DBNhap,sum(qry1.SLXuat) as SLXuat,sum(qry1.SLThungXuat) as DBXuat,sum(qry1.SLNhap-qry1.SLXuat) as SLTon,sum(qry1.SLThungNhap-qry1.SLThungXuat) as DBTonCuoi
                                        from
                                        (SELECT [KhoTP_NK].[MaSP],[KhoTP_NK].[IDNumber],[KhoTP_NK].[LoaiGo],[KhoTP_NK].[SLNhap],[KhoTP_NK].[SLThungNhap],isnull([KhoTP_XK].SLXuat,0) as SLXuat,isnull(SLThungXuat,0) as SLThungXuat,[KhoTP_XK].[Ngay],[KhoTP_XK].[LyDo]
                                            FROM [dbo].[KhoTP_NK] left join [KhoTP_XK] on KhoTP_NK.IDNumber=KhoTP_XK.IDNumber) as qry1 inner join dbo.Load_cbSP on dbo.Load_cbSP.MaSP=qry1.MaSP left join dbo.LyDo on dbo.LyDo.MaLyDo=qry1.LyDo
                                            group by  qry1.MaSP,dbo.Load_cbSP.TenSP,dbo.LyDo.LyDo,qry1.LoaiGo";
                        GhiChu1 = "Lý do được xác định theo lý do xuất";
                        if (cb_MaSPReport.Text != "")
                            string_temp += " where MaSP='" + MaSP1;
                    }
                    if (chk_XuattheoTG.Checked == true) 
                    {
                        
                            if (txt_NgayBegin.Text != "" && txt_NgayEnd.Text != "")
                            {
                                string[] temp = txt_NgayBegin.Text.Split('/');
                                Ngay_start1 = temp[1] + "/" + temp[0] + "/" + temp[2];
                                string[] temp2 = txt_NgayEnd.Text.Split('/');
                                Ngay_End1 = temp2[1] + "/" + temp2[0] + "/" + temp2[2];
                                string_temp = @"select qry1.MaSP,dbo.Load_cbSP.TenSP,dbo.LyDo.LyDo as LyDoNhap,qry1.SLXuat,qry1.DBXuat
                                                from
                                                (SELECT [KhoTP_XK].[MaSP],sum([KhoTP_XK].[SLXuat]) as SLXuat,sum([KhoTP_XK].[SLThungXuat]) as DBXuat,[KhoTP_XK].[LyDo]
                                                FROM [dbo].[KhoTP_XK] where Ngay>='" + Ngay_start1 + "' and Ngay<='" + Ngay_End1 + "' group by [KhoTP_XK].[LyDo],MaSP) as qry1 inner join dbo.Load_cbSP on Load_cbSP.MaSP=qry1.MaSP left join LyDo on LyDo.MaLyDo=qry1.LyDo";
                                GhiChu1 = "Lý do được xác định theo lý do xuất từ ngày: " + txt_NgayBegin.Text + " đến " + txt_NgayEnd.Text;
                            }
                            else
                            {
                                MessageBox.Show("Nhập đầy đủ ngày tháng");
                                string_temp = "";
                            }
                        
                    }
                }
                if (rd_BienBanXuat.Checked == true)
                {
                    string[] temp = txt_NgayBegin.Text.Split('/');
                    Ngay_start1 = temp[1] + "/" + temp[0] + "/" + temp[2];
                    string[] temp2 = txt_NgayEnd.Text.Split('/');
                    Ngay_End1 = temp2[1] + "/" + temp2[0] + "/" + temp2[2];
                    cmd.Parameters.AddWithValue("@datebegin", Ngay_start1);
                    cmd.Parameters.AddWithValue("@dateend", Ngay_End1);
                    cmd.CommandText = "prc_KTP_TH_BB";
                    Ngay_start1 = "Ngày " + txt_NgayBegin.Text;
                    Ngay_End1 = " - " + txt_NgayEnd.Text;
                }
                if(rd_ThucXuat.Checked==false&&rd_LyDoNhap.Checked==false&&rd_LyDoXuat.Checked==false)
                    ds = prs.dts_sql(cmd);
                if(rd_ThucXuat.Checked==true||rd_LyDoNhap.Checked==true||rd_LyDoXuat.Checked==true)
                    ds=prs.dts(string_temp);
                
                if (ds.Tables[0].Rows.Count > 0)
                {
                    Fr_Report FrR = new Fr_Report();
                    //MessageBox.Show(ds.Tables[0].Rows.Count.ToString());
                    if (rd_NhapXuatNgay.Checked == true)
                        FrR.report_KTPTH_Ngay(ds, Ngay_start1, Ngay_End1);
                    if (rd_NhapXuatTuan.Checked == true||rd_NhapXuatThang.Checked==true)
                    {
                        if(chk_statistic.Checked==false)
                            FrR.report_KTPTHNX_Tuan(ds, Ngay_start1, Ngay_End1);
                        if(chk_statistic.Checked==true)
                            FrR.report_KTPStatistic_Tuan(ds, Ngay_start1, Ngay_End1);
                    }
                    if (rd_LyDoNhap.Checked == true || rd_LyDoXuat.Checked == true)
                    {
                       
                        FrR.report_KTPTHLyDo(ds, GhiChu1);
                    }
                    if (rd_BienBanXuat.Checked == true)
                        FrR.report_KTPTH_BB(ds, Ngay_start1, Ngay_End1);
                    if (rd_ThucXuat.Checked == true)
                        FrR.report_KTPTX(ds);
                    FrR.Show();
                    ds.Clear();
                    cmd.Dispose();
                    cmd1.Dispose();
                    Conn.Close();
                }
                else
                    MessageBox.Show("Không có dữ liệu");
                
            }
            catch (Exception ex)
            {
                MessageBox.Show("Kiểm tra lại thông tin tìm kiếm (ngày, tháng....) \n " + ex.Message);
            }
        }

        private void bt_printreport_Click(object sender, EventArgs e)
        {
            report_TH();
        }

        private void bt_excelreport_Click(object sender, EventArgs e)
        {
            Process prs = new Process();
            SqlConnection Conn = prs.Connect();
            SqlCommand cmd = new SqlCommand();
            try
            {
                string check = @"select GroupUser from dbo.Users where UsersName='" + lb_user.Text + "'";
                Conn.Open();
                cmd.CommandText = check;
                cmd.Connection = Conn;
                check = cmd.ExecuteScalar().ToString();
                if (check == "thongke" || check == "admin")
                {
                    if (txt_NgayBegin.Text != "" && txt_NgayEnd.Text != "")
                    {
                        string[] temp = txt_NgayBegin.Text.Split('/');
                        Ngay_start1 = temp[1] + "/" + temp[0] + "/" + temp[2] + " 00:00:00";
                        string[] temp2 = txt_NgayEnd.Text.Split('/');
                        Ngay_End1 = temp2[1] + "/" + temp2[0] + "/" + temp2[2] + " 23:59:59";
                        string temp_string = @"select qry1.* from (SELECT [Serial]
                          ,[ChungTu]
                          ,[MaSP]
                          ,[ArticleNumber]
                          ,[IDNumber]
                          ,[SoHD]
                          ,[KhachHang]
                          ,[LoaiGo]
                          ,[DVGC]
                          ,[SoBB]
                          ,[SLNhap]
                          ,[SLThungNhap]
                          ,SLXuat=0
                          ,SLThungXuat=0
                          ,[DVT]
                          ,[Ngay]
                          ,[ViTri]
     
                          ,[NgayInsert]
                          ,[GhiChu]
                          ,[LyDo]
                        
                      FROM [dbo].[KhoTP_NK]
                      union all
                      SELECT [Serial]
                          ,[ChungTu]
                          ,[MaSP]
                          ,[ArticleNumber]
                          ,[IDNumber]
                          ,[SoHD]
                          ,[KhachHang]
                          ,[LoaiGo]
                          ,[DVGC]
                          ,[SoBB]
                          ,SLNhap=0
                          ,SLThungNhap=0
                          ,[SLXuat]
                          ,[SLThungXuat]
                          ,[DVT]
                          ,[Ngay]
                          ,[ViTri]
     
                          ,[NgayInsert]
                          ,[GhiChu]
                          ,[LyDo]
                         
                      FROM [dbo].[KhoTP_XK]) as qry1 where qry1.Ngay>='" + Ngay_start1 + "' and qry1.Ngay<='" + Ngay_End1 + "'";

                        DataSet ds = new DataSet();

                        ds = prs.dts(temp_string);
                        prs.ExportExcel(ds.Tables[0], "C:\\Huynh\\KhoTP_Data.xlsx", 6, 1);
                        ds.Clear();
                    }
                    else
                        MessageBox.Show("Nhập đầy đủ ngày tháng năm để xuất file");

                }
                else
                    MessageBox.Show("Bạn không có quyền sử dụng chức năng này");

            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
            finally
            {
                Conn.Close();
                cmd.Dispose();
            }
        }
        /*private void ExportExcel(DataTable dt, string sheetName)
        {

            Microsoft.Office.Interop.Excel.Application ExcelObj = new Microsoft.Office.Interop.Excel.Application();
            Microsoft.Office.Interop.Excel.Workbook theWorkbook = ExcelObj.Workbooks.Open(@"C:\\Huynh\\KTP.xlsx", 0, true, 5, "", "", true, Microsoft.Office.Interop.Excel.XlPlatform.xlWindows, "\t", false, false, 0, true, false, Microsoft.Office.Interop.Excel.XlCorruptLoad.xlNormalLoad);
            Microsoft.Office.Interop.Excel.Sheets sheet = theWorkbook.Worksheets;
            Microsoft.Office.Interop.Excel.Worksheet worksheet = (Microsoft.Office.Interop.Excel.Worksheet)sheet.get_Item(1);
            //worksheet.Activate();
            object[,] arr = new object[dt.Rows.Count, dt.Columns.Count];
            //Chuyển dữ liệu từ DataTable vào mảng đối tượng
            for (int r = 0; r < dt.Rows.Count; r++)
            {
                DataRow dr = dt.Rows[r];
                for (int c = 0; c < dt.Columns.Count; c++)
                {
                    //DataRow dr = dt.Rows[r];
                    arr[r, c] = dr[c];
                }
            }

            //Thiết lập vùng điền dữ liệu
            int rowStart = 6;
            int columnStart = 1;

            int rowEnd = rowStart + dt.Rows.Count - 1;
            //int rowEnd = rowStart + dt.Columns.Count - 1;

            int columnEnd = columnStart + dt.Columns.Count - 1;
            //int columnEnd = dt.Rows.Count - 1 + columnStart;

            // Ô bắt đầu điền dữ liệu
            Microsoft.Office.Interop.Excel.Range c1 = (Microsoft.Office.Interop.Excel.Range)worksheet.Cells[rowStart, columnStart];
            // Ô kết thúc điền dữ liệu
            Microsoft.Office.Interop.Excel.Range c2 = (Microsoft.Office.Interop.Excel.Range)worksheet.Cells[rowEnd, columnEnd];
            // Lấy về vùng điền dữ liệu
            Microsoft.Office.Interop.Excel.Range range = worksheet.get_Range(c1, c2);

            //Điền dữ liệu vào vùng đã thiết lập
            range.Value2 = arr;
            //range.Columns.AutoFit();
            range.Borders.LineStyle = Microsoft.Office.Interop.Excel.Constants.xlSolid;
            //theWorkbook=theWorkbook.Open("C:\\test.xlsx");
            //worksheet = ("sheet1");
            //range.Activate();
            object misValue = System.Reflection.Missing.Value;
            theWorkbook.Close(true, misValue, misValue);
            ExcelObj.Quit();

        }*/
        public void Users(string Users)
        {
            lb_user.Text = Users;
        }

        private void FrKhoThanhPham_KeyDown(object sender, KeyEventArgs ex)
        {
            if (ex.KeyData == Keys.Enter)
            {
                SendKeys.Send("{TAB}");
            }
            if (ex.KeyCode == Keys.F11)
            {
                if (dataGridView1.Rows.Count > 1)
                {
                    bt_saveinput_Click(null, null);
                }
            }
            if (ex.KeyCode == Keys.F12)
            {
                if (dataGridView3.Rows.Count > 1)
                {
                    if (bt_saveoutput.Enabled == true)
                        bt_saveoutput_Click(null, null);
                    else
                        MessageBox.Show("Bạn chưa mở chức năng này");
                }
            }
            if (ex.KeyCode == Keys.F3)
            {
                SoDoKho();
            }
            if (ex.KeyCode == Keys.End)
            {
                if (tab_control.SelectedTab == tab_Nhap)
                {
                    bt_insertinput_Click(null, null);
                }
                if (tab_control.SelectedTab == tab_Xuat)
                {
                    bt_insertoutput_Click(null, null);
                }
            }
            if (ex.KeyCode == Keys.F2)
            {
                if(txt_printCT.Text!="")
                    print_ChungTu(txt_printCT.Text);
            }
            if (ex.KeyCode == Keys.F1)
            {
                print_Xuat();
                //print_ChungTu(txt_printCT.Text);
                txt_printCT.Visible = false;
            }
            if (ex.KeyCode == Keys.F4)
            {
                KiemKe_ViTri();
            }
        }

        private void rd_NhapXuatNgay_CheckedChanged(object sender, EventArgs e)
        {
            lb_NgayBegin.Text = "Từ Ngày";
            lb_NgayEnd.Text = "Đến Ngày";
            txt_Nam.Visible = false;
            lb_Nam.Visible = false;
            txt_NgayBegin.Text = "";
            txt_NgayEnd.Text = "";
            chk_XuattheoTG.Visible = false;
            chk_NhaptheoTG.Visible = false;
            chk_statistic.Visible = false;
        }

        private void rd_NhapXuatTuan_CheckedChanged(object sender, EventArgs e)
        {
            lb_NgayBegin.Text = "Từ Tuần";
            lb_NgayEnd.Text = "Đến Tuần";
            txt_Nam.Visible = true;
            lb_Nam.Visible = true;
            txt_NgayBegin.Text = "";
            txt_NgayEnd.Text = "";
            chk_statistic.Visible = true;
        }

        private void lb_user_TextChanged(object sender, EventArgs e)
        {
            Check_User();
        }

        private void txt_SLoutput_Leave(object sender, EventArgs e)
        {
            try
            {
                //check_TonKho();
            }
            catch
            {
            }
        }

        private void dataGridView1_DoubleClick_1(object sender, EventArgs e)
        {
            if (dataGridView1.Rows.Count > 1)
            {
                try
                {
                    int r = dataGridView1.CurrentCell.RowIndex;
                    //MessageBox.Show(r.ToString());
                    Tong1 = double.Parse(lb_Tong.Text) - double.Parse(dataGridView1.Rows[r].Cells["SLinput"].Value.ToString());
                    lb_Tong.Text = string.Format("{0:###,###}", Tong1);
                    dataGridView1.Rows.RemoveAt(r);
                    //MessageBox.Show("aaaa");
                    int j = dataGridView1.Rows.Count - 1;
                    dataGridView1.CurrentCell = dataGridView1.Rows[j].Cells["MaSPinput"];
                }
                catch (Exception ex)
                { MessageBox.Show(ex.Message); }
            }
            if (dataGridView1.Rows.Count == 1)
                lb_Tong.Text = "0";
        }

        private void dataGridView3_DoubleClick_1(object sender, EventArgs e)
        {
            /*if (dataGridView3.Rows.Count > 1)
            {
                try
                {
                    int r = dataGridView3.CurrentCell.RowIndex;
                    //MessageBox.Show(r.ToString());
                    Tong1 = double.Parse(lb_TongXuat.Text) - double.Parse(dataGridView3.Rows[r].Cells["SLoutput"].Value.ToString());
                    lb_TongXuat.Text = string.Format("{0:###,###}", Tong1);
                    dataGridView3.Rows.RemoveAt(r);
                    //MessageBox.Show("aaaa");
                    int j = dataGridView3.Rows.Count - 1;
                    dataGridView3.CurrentCell = dataGridView3.Rows[j].Cells["MaSPoutput"];
                }
                catch (Exception ex)
                { MessageBox.Show(ex.Message); }
            }
            if (dataGridView3.Rows.Count == 1)
                lb_TongXuat.Text = "0";*/
        }

        private void lb_LyDoNhap_DoubleClick(object sender, EventArgs e)
        {
            cb_LyDoNhap.Enabled = true;
        }

        private void lb_LyDoXuat_DoubleClick(object sender, EventArgs e)
        {
            cb_LyDoXuat.Enabled = true;
        }

        private void bt_resetinput_Click(object sender, EventArgs e)
        {
            bt_insertinput.Enabled = true;
            if (dataGridView2.Rows.Count > 1)
            {
                for (i = dataGridView2.Rows.Count - 2; i >= 0; i--)
                {
                    dataGridView2.Rows.RemoveAt(i);
                }
            }
            cb_LyDoNhap.Text = "NHAP MOI - TPNM";
            lb_serialinput.Text = "0";
            cb_MaSPinput.Text = "";
            cb_DVGCinput.Text = "";
            txt_GhiChuinput.Text = "";
            cb_KhachHanginput.Text = "";
            txt_SLinput.Text = "";
            txt_SoBBinput.Text = "";
            txt_SoHDinput.Text = "";
            txt_SoThunginput.Text = "";
            txt_IDNumberinput.Text = "";
            txt_ArticleNumberinput.Text = "";
            txt_ArticleNumberinput.Focus();
            cb_ViTriinput.Enabled = true;
            date_default.Checked = true;
        }

        private void cb_LoaiGooutput_SelectedIndexChanged(object sender, EventArgs e)
        {
            TonKho();
        }
        private void bt_resetoutput_Click(object sender, EventArgs e)
        {
            bt_insertoutput.Enabled = true;
            txt_ArticleNumberoutput.Text = "";
            txt_IDNumberoutput.Text = "";
            cb_LyDoXuat.Text = "XUAT BAN - TPXB";
            lb_serialoutput.Text = "0";
            cb_MaSPoutput.Text = "";
            cb_DVGCoutput.Text = "";
            txt_GhiChuoutput.Text = "";
            cb_KhachHangoutput.Text = "";
            txt_SLoutput.Text = "";
            txt_SoBBoutput.Text = "";
            txt_SoHDoutput.Text = "";
            txt_SLThungoutput.Text = "";
            bt_editoutput.Enabled = false;
            bt_deleteoutput.Enabled = false;
            txt_SoCT.Text = "";
            lb_CT.Visible = false;
            txt_SoCT.Enabled = false;
            bt_addproduct.Enabled = false;
        }
        private void print_ChungTu(string SoChungTu)
        {
            try
            {
                Process prs = new Process();

                GhiChu1 = @"select KhoTP_ChungTu.MaCT as ChungTu,KhoTP_ChungTu.SoBB,KhoTP_ChungTu.MaKH as TenKH, qry1.MaSP,KhoTP_ChungTu.SoHD as HDNgay,dbo.Load_cbSP.TenSP,qry1.LoaiGo,convert(varchar(10),KhoTP_ChungTu.Ngay,103) as NgayNhap,qry1.SLXuat,qry1.DBXuat,qry1.SoLuong,LyDo.LyDo as LyDoNhap from
                        (select KhoTP_XK.MaSP,KhoTP_XK.ChungTu,sum(dbo.KhoTP_XK.SLXuat) as SLXuat,sum(dbo.KhoTP_XK.SLThungXuat) as DBXuat,count(SLThungXuat) as SoLuong,dbo.KhoTP_XK.LoaiGo,LyDo
                        from dbo.KhoTP_XK group by MaSP,LyDo,ChungTu,LoaiGo) as qry1
                        inner join KhoTP_ChungTu on KhoTP_ChungTu.MaCT=qry1.ChungTu inner join dbo.Load_cbSP on dbo.Load_cbSP.MaSP=qry1.MaSP left join LyDo on LyDo.MaLyDo=qry1.LyDo
                        where KhoTP_ChungTu.MaCT=" +txt_printCT.Text;
                DataSet ds = prs.dts(GhiChu1);

                Fr_Report FrR = new Fr_Report();
                // Ngay1 = txt_Ngayinput.Text;
                FrR.report_KTPXK(ds);
                FrR.Show();
                ds.Clear();
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }

        }

        private void FrKhoThanhPham_KeyUp(object sender, KeyEventArgs e)
        {
            if (e.Control)
            {
                if (e.KeyCode.Equals(Keys.P))
                {
                    try
                    {
                        print_ChungTu(lb_Chungtu.Text);
                    }
                    catch (Exception ex)
                    {
                        MessageBox.Show(ex.Message);
                    }
                }
                if (e.KeyCode.Equals(Keys.G))
                {
                    link_NhomViTri_LinkClicked(null, null);
                }
                if (e.KeyCode.Equals(Keys.N))
                {
                    bt_addproduct.Enabled = true;
                  
                }
                if (e.KeyCode.Equals(Keys.Insert))
                {
                    Process prs = new Process();
                    SqlConnection Conn = prs.Connect();
                    SqlCommand cmd = new SqlCommand();
                    Conn.Open();
                    cmd.Connection = Conn;
                    try
                    {
                        string check = @"select GroupUser from dbo.Users where UsersName='" + lb_user.Text + "'";
                        cmd.Connection = Conn;
                        cmd.CommandText = check;
                        //MessageBox.Show(check);
                        check = cmd.ExecuteScalar().ToString();
                        if (check == "qlktp" || check == "admin")
                        {
                            tab_QLKho.Visible = true;
                        }
                        else
                        {
                            MessageBox.Show("Bạn không được phép sử dụng chức năng này");
                        }
                    }
                    catch (Exception ex)
                    {
                        MessageBox.Show(ex.Message);
                    }
                }
                if(e.KeyCode.Equals(Keys.M))
                {
                    bt_closeout.Visible = true;
                }
            }
        }

        private void linkLabel1_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
        {
            txt_printCT.Visible = true;
        }

       
        private void print_Nhap()
        {
            try
            {
                if (txt_Ngayinput.Text != "")
                {
                    Process prs = new Process();
                    Ngay1 = txt_Ngayinput.Text;
                    string[] temp = Ngay1.Split('/');
                    Ngay1 = temp[1] + "/" + temp[0] + "/" + temp[2];
                    string print_NKTG = @"select dbo.Load_cbSP.MaSP,dbo.Load_cbSP.TenSP,KhoTP_NK.ChungTu,dbo.KhoTP_NK.SLNhap,dbo.KhoTP_NK.SLThungNhap as DBNhap,dbo.KhoTP_NK.LoaiGo,dbo.KhoTP_NK.KhachHang as TenKH,dbo.KhoTP_NK.DVT,LyDo.LyDo as LyDoNhap,convert(varchar(5),dbo.KhoTP_NK.NgayInsert,108) as Ngay,Serial as Serial_NK,KhoTP_NK.IDNumber as ADorKD,left(KhoTP_NK.ArticleNumber,11) as FCS,dbo.KhoTP_NK.ViTri as DiaChi
                                            from dbo.KhoTP_NK inner join dbo.Load_cbSP on dbo.KhoTP_NK.MaSP=dbo.Load_cbSP.MaSP inner join LyDo on LyDo.MaLyDo=KhoTP_NK.LyDo";
                    if (cb_MaSPinput.Text == "")
                    {
                        print_NKTG += @" where SLNhap <>0 and Ngay='" + Ngay1 + "' order by Serial";
                    }
                    else
                    {
                        MaSP1 = prs.substring_right(cb_MaSPinput.Text, child);
                        print_NKTG += @" where SLNhap <>0 and Ngay='" + Ngay1 + "' and dbo.Load_cbSP.MaSP='"+MaSP1+"' order by Serial";
                    }
                    DataSet ds = prs.dts(print_NKTG);
                    Fr_Report FrR = new Fr_Report();
                    Ngay1 = txt_Ngayinput.Text;
                    FrR.report_KTPNK(ds, Ngay1);
                    FrR.Show();
                    ds.Clear();

                }
                else
                    MessageBox.Show("Chọn ngày cần in");
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }
        private void print_Xuat()
        {
            try
            {
                if (txt_Ngayoutput.Text != "")
                {
                    check = "0";
                    Process prs = new Process();
                    Ngay1 = txt_Ngayoutput.Text;
                    string[] temp = Ngay1.Split('/');
                    Ngay1 = temp[1] + "/" + temp[0] + "/" + temp[2];
                    string print_NKTG = @"select dbo.Load_cbSP.MaSP,dbo.Load_cbSP.TenSP,KhoTP_XK.ChungTu,dbo.KhoTP_XK.SLXuat,dbo.KhoTP_XK.SLThungXuat as DBXuat,dbo.KhoTP_XK.LoaiGo,dbo.KhoTP_XK.KhachHang as TenKH,dbo.KhoTP_XK.DVT,LyDo.LyDo as LyDoNhap,convert(varchar(5),dbo.KhoTP_XK.NgayInsert,108) as Ngay,Serial as Serial_NK,dbo.KhoTP_XK.IDNumber as FCS,left(dbo.KhoTP_XK.ArticleNumber,11) as ADorKD,dbo.KhoTP_XK.ViTri as DiaChi
                                            from dbo.KhoTP_XK inner join dbo.Load_cbSP on dbo.KhoTP_XK.MaSP=dbo.Load_cbSP.MaSP inner join LyDo on LyDo.MaLyDo=KhoTP_XK.LyDo";
                    if (txt_printCT.Visible == true)
                    {
                        check = "1";
                        if (txt_printCT.Text != "")
                        {
                            print_NKTG = @"select dbo.Load_cbSP.MaSP,dbo.Load_cbSP.TenSP,KhoTP_XK.ChungTu,dbo.KhoTP_XK.SLXuat,dbo.KhoTP_XK.SLThungXuat as DBXuat,dbo.KhoTP_XK.LoaiGo,dbo.KhoTP_XK.KhachHang as TenKH,dbo.KhoTP_XK.DVT,LyDo.LyDo as LyDoNhap,convert(varchar(10),dbo.KhoTP_XK.Ngay,103) as Ngay,Serial as Serial_NK,dbo.KhoTP_XK.IDNumber as FCS,left(dbo.KhoTP_XK.ArticleNumber,11) as ADorKD,dbo.KhoTP_XK.ViTri as DiaChi
                                            from dbo.KhoTP_XK inner join dbo.Load_cbSP on dbo.KhoTP_XK.MaSP=dbo.Load_cbSP.MaSP inner join LyDo on LyDo.MaLyDo=KhoTP_XK.LyDo where SLXuat <>0 and ChungTu=" + txt_printCT.Text+ "order by Serial";
                            Ngay1 = "";
                        }
                        else
                        {

                            MessageBox.Show("In tất cả các sản phẩm đã xuất");
                            print_NKTG = @"select dbo.Load_cbSP.MaSP,dbo.Load_cbSP.TenSP,KhoTP_XK.ChungTu,dbo.KhoTP_XK.SLXuat,dbo.KhoTP_XK.SLThungXuat as DBXuat,dbo.KhoTP_XK.LoaiGo,dbo.KhoTP_XK.KhachHang as TenKH,dbo.KhoTP_XK.DVT,LyDo.LyDo as LyDoNhap,convert(varchar(10),dbo.KhoTP_XK.Ngay,103) as Ngay,Serial as Serial_NK,dbo.KhoTP_XK.IDNumber as FCS,left(dbo.KhoTP_XK.ArticleNumber,11) as ADorKD,dbo.KhoTP_XK.ViTri as DiaChi
                                            from dbo.KhoTP_XK inner join dbo.Load_cbSP on dbo.KhoTP_XK.MaSP=dbo.Load_cbSP.MaSP inner join LyDo on LyDo.MaLyDo=KhoTP_XK.LyDo order by KhoTP_XK.Ngay";
                            Ngay1 = "Danh sách tất cả các lô hàng đã xuất";
                        }
              }
                    if (txt_printCT.Visible == false) 
                    {
                        if (cb_MaSPoutput.Text == "")
                        {
                            print_NKTG += @" where SLXuat <>0 and Ngay='" + Ngay1 + "' order by KhoTP_XK.ViTri";
                        }
                        else
                        {
                            MaSP1 = prs.substring_right(cb_MaSPoutput.Text, child);
                            print_NKTG += @" where SLXuat <>0 and Ngay='" + Ngay1 + "' and dbo.Load_cbSP.MaSP='" + MaSP1 + "' order by KhoTP_XK.ViTri";
                        }
                    }
                    //MessageBox.Show(print_NKTG);
                    DataSet ds = prs.dts(print_NKTG);
                    Fr_Report FrR = new Fr_Report();
                    if(check=="0")
                        Ngay1 = txt_Ngayoutput.Text;
                    FrR.report_KTPXK_Ngay(ds, Ngay1);
                    FrR.Show();
                    ds.Clear();

                }
                else
                    MessageBox.Show("Chọn ngày cần in");
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }

        private void rd_LyDo_CheckedChanged(object sender, EventArgs e)
        {
            lb_NgayBegin.Text = "Từ Ngày";
            lb_NgayEnd.Text = "Đến Ngày";
            txt_Nam.Visible = false;
            lb_Nam.Visible = false;
            txt_NgayBegin.Text = "";
            txt_NgayEnd.Text = "";
            chk_NhaptheoTG.Visible = true;
            chk_XuattheoTG.Visible = true;
            chk_statistic.Visible = false;
        }
        private void SoDoKho()
        {
            try
            {
                Microsoft.Office.Interop.Excel.Application ExcelObj = new Microsoft.Office.Interop.Excel.Application();
                ExcelObj.Visible = true;

                Microsoft.Office.Interop.Excel.Workbook theWorkbook = ExcelObj.Workbooks.Open("C:\\Huynh\\SoDoKho.xlsx", 0, true, 5, "", "", true, Microsoft.Office.Interop.Excel.XlPlatform.xlWindows, "\t", false, false, 0, true, false, Microsoft.Office.Interop.Excel.XlCorruptLoad.xlNormalLoad);
                Microsoft.Office.Interop.Excel.Sheets sheet = theWorkbook.Worksheets;
                Microsoft.Office.Interop.Excel.Worksheet worksheet = (Microsoft.Office.Interop.Excel.Worksheet)sheet.get_Item(1);
                //object misValue = System.Reflection.Missing.Value;
                //theWorkbook.Close(true, misValue, misValue);
                //ExcelObj.Quit();
               
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }

        private void linkLabel2_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
        {
            SoDoKho();
        }

        
        private void txt_ArticleNumberinput_Leave(object sender, EventArgs e)
        {
            if (txt_ArticleNumberinput.Text.Length > 30)
            {
                MessageBox.Show("Vượt quá số lần cho phép");
                txt_ArticleNumberinput.Text = "";
                txt_ArticleNumberinput.Focus();
            }
            else
            {
                add_parameter();
            }
        }

        private void txt_IDNumberinput_Leave(object sender, EventArgs e)
        {
            try
            {
                if (txt_IDNumberinput.Text.Length > 20)
                {
                    MessageBox.Show("Vượt quá số lần cho phép");
                    txt_IDNumberinput.Text = "";
                    txt_IDNumberinput.Focus();
                }

                Process prs = new Process();
                MaSP1 = prs.substring_right(cb_MaSPinput.Text, child);
                for (j = dataGridView6.Rows.Count - 2; j >= 0; j--)
                {
                    if (MaSP1 == dataGridView6.Rows[j].Cells["MaSP_AddViTri"].Value.ToString())
                    {
                        cb_ViTriinput.Text = dataGridView6.Rows[j].Cells["ViTri_AddViTri"].Value.ToString();
                        break;
                    }
                  
                }
            }
            catch
            {
            }
        }
        private bool sosanh(string S1,string S2) //Kiem tra chuoi S2 co trong S1 hay ko
        {
            return S1.Contains(S2);
        }
        private void add_parameter()
        {
            if (txt_ArticleNumberinput.Text != "")
            {
                try
                {
                    check = txt_ArticleNumberinput.Text.Trim();
                    for (i = 0; i < dataGridView7.Rows.Count - 1; i++)
                    {
                        string_temp = dataGridView7.Rows[i].Cells["ArticleNumber"].Value.ToString();
                        if (sosanh(check, string_temp))
                        {
                            cb_MaSPinput.Text = dataGridView7.Rows[i].Cells["MaSP"].Value.ToString();
                            txt_SLinput.Text = dataGridView7.Rows[i].Cells["SLuong"].Value.ToString();

                            txt_SoThunginput.Text = dataGridView7.Rows[i].Cells["SLuong"].Value.ToString();
                            lb_Articlenumber.Text = dataGridView7.Rows[i].Cells["ArticleNumber"].Value.ToString();
                            break;
                        }
                    }

                    if (i == dataGridView7.Rows.Count - 1)
                    {
                        MessageBox.Show("Mã vạch không đúng");
                        txt_ArticleNumberinput.Text = "";
                        txt_ArticleNumberinput.Focus();
                    }
                   
                        
                   
                }
                catch (Exception ex)
                {
                    MessageBox.Show("Có lỗi xảy ra, vui lòng kiểm tra lại",ex.Message);
                }
            }
        }
        private void ViTri_edit()
        {
            Process prs = new Process();
            SqlConnection Conn = prs.Connect();
            SqlCommand cmd = new SqlCommand();
            Conn.Open();
            cmd.Connection = Conn;
            cmd.CommandType = CommandType.StoredProcedure;
            cmd.CommandText = "Upd_KTPVT";
            if (txt_ViTriVT.Text == "" || txt_ViTri_Chuyenoutput.Text == "")
                MessageBox.Show("Nhập thiếu vị trí");
            else
            {
                try
                {
                    DialogResult d = MessageBox.Show("Bạn có chắc muốn sửa lại vị trí có Số Serial " + txt_Serial_VT.Text, "Thông Báo", MessageBoxButtons.OKCancel);

                    if (d == DialogResult.OK)
                    {
                        cmd.Parameters.AddWithValue("@Serial", txt_Serial_VT.Text);
                        cmd.Parameters.AddWithValue("@ViTri1", txt_ViTriVT.Text);
                        cmd.Parameters.AddWithValue("@ViTri2", txt_ViTri_Chuyenoutput.Text);
                        
                        cmd.ExecuteNonQuery();
                        MessageBox.Show("Chuyển thành công");
                        for (i = dataGridView8.Rows.Count - 2; i >= 0; i--)
                        {
                            dataGridView8.Rows.RemoveAt(i);
                        }
                        txt_Serial_VT.Text = "";
                        txt_Serial_VT.Enabled = true;
                        txt_ViTriVT.Text = "";
                        txt_ViTri_Chuyenoutput.Text = "";
                        txt_IDNumberVT.Text = "";
                        lb_serialinput.Text = "Khong ton tai";
                        lb_serialoutput.Text = "Khong ton tai";
                        
                    }
                }
                catch (Exception ex)
                {
                    MessageBox.Show(ex.Message);
                }
                finally
                {
                    Conn.Close();
                    cmd.Dispose();
                }
            }
        }
        private void bt_editVT_Click(object sender, EventArgs e)
        {
            ViTri_edit();
        }
        private void Vitri_Search()
        {
            Process prs=new Process();
            DataSet ds = new DataSet();
            string_temp = @"SELECT     dbo.KhoTP_NK.Serial, dbo.KhoTP_NK.IDNumber, dbo.Load_cbSP.MaSP,dbo.Load_cbSP.TenSP, dbo.KhoTP_NK.SLNhap, convert(varchar(10),dbo.KhoTP_NK.Ngay,103) as NgayInsert,dbo.KhoTP_NK.Ngay, dbo.KhoTP_NK.ViTri
                            FROM         dbo.KhoTP_NK  LEFT OUTER JOIN
                      dbo.KhoTP_XK ON dbo.KhoTP_NK.IDNumber = dbo.KhoTP_XK.IDNumber inner join dbo.Load_cbSP on Load_cbSP.MaSP=dbo.KhoTP_NK.MaSP where dbo.KhoTP_XK.IDNumber IS NULL";
            try
            {
               
                if (txt_Serial_VT.Text != "")
                {
                    string_temp += " and dbo.KhoTP_NK.Serial=" + txt_Serial_VT.Text;
                }
                else
                {
                    if (txt_IDNumberVT.Text != "")
                    {
                        string_temp += " and dbo.KhoTP_NK.IDNumber like'%" + txt_IDNumberVT.Text + "%'";
                    }
                    else
                    {
                        if (cb_TenSP_VT.Text != "")
                        {
                            MaSP1 = prs.substring_right(cb_TenSP_VT.Text, child);
                            if (MaSP1 == "")
                                MessageBox.Show("Nhập sai thông tin Sản Phẩm");
                            else
                            {

                                string_temp += " and dbo.Load_cbSP.MaSP='" + MaSP1 + "'";
                            }
                        }
                    }
                }
                //MessageBox.Show(string_temp);
                ds = prs.dts(string_temp);
                if (ds.Tables[0].Rows.Count > 0)
                {
                    dataGridView8.DataSource = ds.Tables[0];
                    prs.formatcolordatagrid(dataGridView8);
                }
                else
                    MessageBox.Show("Không có dữ liệu, vui lòng kiểm tra lại thông tin tìm kiếm");
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
            
        }
        private void bt_TimVT_Click(object sender, EventArgs e)
        {
            Vitri_Search();
        }
        private void Display_ViTri(int r)
        {
            txt_IDNumberVT.Text = dataGridView8.Rows[r].Cells["IDNumberVT"].Value.ToString();
            txt_Serial_VT.Text = dataGridView8.Rows[r].Cells["SerialVT"].Value.ToString();
            txt_NgayVT.Text = dataGridView8.Rows[r].Cells["NgayView"].Value.ToString();
           
            txt_SLVT.Text = dataGridView8.Rows[r].Cells["SLNhapVT"].Value.ToString();
           
            cb_TenSP_VT.Text = dataGridView8.Rows[r].Cells["TenSPVT"].Value.ToString();
           
            txt_ViTriVT.Text = dataGridView8.Rows[r].Cells["ViTriVT"].Value.ToString();
           
           
            txt_ViTriVT.Enabled = false;
            txt_Serial_VT.Enabled = false;
        }

        private void dataGridView8_Click(object sender, EventArgs e)
        {
            try
            {
                if (dataGridView8.Rows.Count > 1)
                {
                    int r = dataGridView8.CurrentCell.RowIndex;
                    Display_ViTri(r);
                }

            }
            catch(Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }

        private void cb_MaSP_TKVT_SelectedIndexChanged(object sender, EventArgs e)
        {
           
        }
        private void load_SPChuaXuat()
        {
            if (cb_KhachHangoutput.Text == "" || cb_LyDoXuat.Text == ""||txt_SoHDoutput.Text==""||cb_MaSPoutput.Text=="")
                MessageBox.Show("Bạn cần nhập đầy đủ Tên SP,Ngày, Khách Hàng, Hợp Đồng và Lý Do xuất");
            else
            {
                Process prs = new Process();
                MaSP1 = prs.substring_right(cb_MaSPoutput.Text, child);
                string_temp = @"select * from KhoTP_SPChuaXuat where MaSP='"+MaSP1+"' ";
                if (txt_ArticleNumberoutput.Text != "")
                {
                    string_temp += " and ArticleNumber like '%" + txt_ArticleNumberoutput.Text + "%'";
                }
                string_temp += " order by Ngay,ViTri";
                DataSet ds = new DataSet();
                try
                {
                    string t;
                    lb_TongXuat.Text = "0";
                    ds = prs.dts(string_temp);
                    if (dataGridView3.Rows.Count > 1)
                        dataGridView3.Rows.Clear();
                    Ngay1 = txt_Ngayoutput.Text;
                    string[] temp = txt_Ngayoutput.Text.Split('/');
                    NgayInsert1 = temp[1] + "/" + temp[0] + "/" + temp[2];
                    LyDo1 = prs.substring_right(cb_LyDoXuat.Text, child);
                    KhachHang1 = cb_KhachHangoutput.Text;
                    SoHD1 = txt_SoHDoutput.Text;
                    SoBB1 = txt_SoBBoutput.Text;
                    for (i = 0; i < ds.Tables[0].Rows.Count; i++)
                    {
                        MaSP1 = ds.Tables[0].Rows[i]["MaSP"].ToString();
                        TenSP1 = ds.Tables[0].Rows[i]["TenSP"].ToString();
                        LoaiGo1 = ds.Tables[0].Rows[i]["LoaiGo"].ToString();
                        SLNhap1 = ds.Tables[0].Rows[i]["SLNhap"].ToString();
                        DVT1 = ds.Tables[0].Rows[i]["DVT"].ToString();
                        SoThung1 = ds.Tables[0].Rows[i]["SLThungNhap"].ToString();
                        ArticleNumber1 = ds.Tables[0].Rows[i]["ArticleNumber"].ToString();
                        IDNumber1 = ds.Tables[0].Rows[i]["IDNumber"].ToString();
                        ViTri1 = ds.Tables[0].Rows[i]["ViTri"].ToString();
                        //SoBB1 = ds.Tables[0].Rows[i]["SoBB"].ToString();
                        DVGC1 = ds.Tables[0].Rows[i]["DVGC"].ToString();
                        GhiChu1 = txt_GhiChuoutput.Text;
                        Kien1 = ds.Tables[0].Rows[i]["Kien"].ToString();
                        t = ds.Tables[0].Rows[i]["Ngay"].ToString();
                        dataGridView3.Rows.Add(false, MaSP1, TenSP1, LoaiGo1, SLNhap1, DVT1, SoThung1, ArticleNumber1, IDNumber1, ViTri1, LyDo1, KhachHang1,Kien1,Ngay1, SoBB1, DVGC1, SoHD1, NgayInsert1, GhiChu1,t);
                        

                    }
                    prs.formatcolordatagrid(dataGridView3);
                    temp.Clone();
                }
                catch (Exception ex)
                {
                    MessageBox.Show(ex.Message);
                }
            }
          
        }

        private void bt_Load_Click(object sender, EventArgs e)
        {
            load_SPChuaXuat();
        }
       
        
        private void check_ViTri(string ViTriXuat)
        {
           
        
       
        }
        #region //Bat su kien checkbox changed trong datagridview
        private void dataGridView3_CurrentCellDirtyStateChanged(object sender, EventArgs e)
        {
            if (dataGridView3.IsCurrentCellDirty)
                dataGridView3.CommitEdit(DataGridViewDataErrorContexts.Commit);
        }

        private void dataGridView3_CellValueChanged(object sender, DataGridViewCellEventArgs e)
        {
            try
            {
                
                if (e.ColumnIndex == 0) //compare to checkBox column index
                {
                    DataGridViewCheckBoxCell chk = (DataGridViewCheckBoxCell)dataGridView3[e.ColumnIndex, e.RowIndex];
                    check = dataGridView3.Rows[e.RowIndex].Cells["ViTrioutput"].Value.ToString();
                    
                    if (!DBNull.Value.Equals(chk.Value) && chk.Value == chk.TrueValue)
                    {
                        cb_ViTrioutput.Text = check;
                        Tong1 = double.Parse(lb_TongXuat.Text);
                        Tong1 += double.Parse(dataGridView3.Rows[e.RowIndex].Cells["SLoutput"].Value.ToString());

                        if (Tong1 != 0)
                            lb_TongXuat.Text = string.Format("{0:###,###.##}", Tong1);
                        else
                            lb_TongXuat.Text = "0";
                    }
                    else
                    {
                        cb_ViTriinput.Text = check;
                        Tong1 = double.Parse(lb_TongXuat.Text);
                        Tong1 -= double.Parse(dataGridView3.Rows[e.RowIndex].Cells["SLoutput"].Value.ToString());
                        if (Tong1 != 0)
                            lb_TongXuat.Text = string.Format("{0:###,###.##}", Tong1);
                        else
                            lb_TongXuat.Text = "0";
                    }
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }
        #endregion

        private void link_NhomViTri_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
        {
            try
            {
                if (cb_ViTrioutput.Text != "")
                {
                    //string[] temp;
                    string parent = cb_ViTrioutput.Text;
                    //string parent = cb_ViTrioutput.Text.Substring(0, 2);
                    j = dataGridView3.Rows.Count - 1;
                    Tong1 = double.Parse(lb_TongXuat.Text);
                    for (i = 0; i < j; i++)
                    {
                        string_temp = dataGridView3.Rows[i].Cells["ViTrioutput"].Value.ToString();
                        if (string_temp==parent)
                        {
                            DataGridViewCheckBoxCell chk = (DataGridViewCheckBoxCell)dataGridView3.Rows[i].Cells["Checkbox"];
                            chk.Value = chk.TrueValue;
                            //Tong1 += double.Parse(dataGridView3.Rows[i].Cells["SLoutput"].Value.ToString());
                        }
                    }
                    if (Tong1 != 0)
                        lb_TongXuat.Text = string.Format("{0:###,###.##}", Tong1);
                    else
                        lb_TongXuat.Text = "0";

                }
                else
                    MessageBox.Show("Vị trí không xác định");
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
                MessageBox.Show("Có thể những chi tiết thuộc vị trí này bạn cần phải chọn từng sản phẩm");
            }
            
        }

        private void tabItem1_Click(object sender, EventArgs e)
        {
            Process prs = new Process();
            try
            {
               


                    string_temp = @"select ViTri,MaSP,SLToiDa,SLTheoDoi,SLToiDa-SLTheoDoi as SLSD from dbo.KhoTP_MatBangKho Order by ViTri";
                    DataSet ds = prs.dts(string_temp);
                    if (dataGridView9.Rows.Count > 1)
                        dataGridView9.Rows.Clear();
                    for (i = 0; i < ds.Tables[0].Rows.Count; i++)
                    {
                        dataGridView9.Rows.Add(false, ds.Tables[0].Rows[i]["ViTri"].ToString(), ds.Tables[0].Rows[i]["MaSP"].ToString(), ds.Tables[0].Rows[i]["SLToiDa"].ToString(), ds.Tables[0].Rows[i]["SLTheoDoi"].ToString(), ds.Tables[0].Rows[i]["SLSD"].ToString());
                        TK_KTP=double.Parse(ds.Tables[0].Rows[i]["SLTheoDoi"].ToString());
                        if (TK_KTP < 6)
                        {
                            if (TK_KTP >= 3 && TK_KTP <= 5)
                                dataGridView9.Rows[i].DefaultCellStyle.BackColor = Color.LemonChiffon;
                            if (TK_KTP < 3 && TK_KTP > 0)
                                dataGridView9.Rows[i].DefaultCellStyle.BackColor = Color.Pink;
                            if (TK_KTP <= 0)
                                dataGridView9.Rows[i].DefaultCellStyle.BackColor = Color.Red;
                        }
                    }
                    ds.Clear();
            }
            catch (Exception ex)
            {
                MessageBox.Show("Có lỗi xảy ra, vui lòng kiểm tra lại", ex.Message);
            }
        }

       

        private void bt_listoutput_Click_1(object sender, EventArgs e)
        {
            Tong1 = 0;
            for (i = dataGridView3.Rows.Count - 2; i >= 0; i--)
            {
                check=dataGridView3.Rows[i].Cells["Checkbox"].Value.ToString();
                
                if (check == "1" || check == "True")
                {
                    Tong1 += double.Parse(dataGridView3.Rows[i].Cells["SLoutput"].Value.ToString());
                }
                if (check == "0" || check == "False")
                {
                    
                    dataGridView3.Rows.RemoveAt(i);
                }
            }
            bt_saveoutput.Enabled = true;
            lb_TongXuat.Text = string.Format("{0:###,###.##}", Tong1);
        }

        private void labelX2_DoubleClick(object sender, EventArgs e)
        {
            string_temp = @"select max(Serial)+1 from dbo.KhoTP_NK";
            Process prs=new Process();
            SqlConnection Conn = prs.Connect();
            SqlCommand cmd = new SqlCommand();
            cmd.Connection = Conn;
            Conn.Open();
            try
            {
                cmd.CommandText = string_temp;
                txt_IDNumberinput.Text = cmd.ExecuteScalar().ToString();
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
            finally
            {
                Conn.Close();
                cmd.Dispose();
            }
        }

        private void cb_MaSPHC_SelectedIndexChanged(object sender, EventArgs e)
        {
            Process prs = new Process();
            SqlConnection Conn = prs.Connect();
            SqlCommand cmd = new SqlCommand();
            try
            {
                Conn.Open();
                cmd.Connection = Conn;
                MaSP1 = prs.substring_right(cb_MaSPHC.Text, child);
                string TonKho1 = @"select isnull(TonKho,0) from dbo.KhoTP_TK where MaSP='" + MaSP1 + "' and LoaiGo='" + cb_LoaiGo_HC.Text + "'";
                MessageBox.Show(TonKho1);
                cmd.CommandText = TonKho1;
                lb_TonKho_HC.Text = cmd.ExecuteScalar().ToString();
                TonKho1 = @"select isnull(SLThung,0) from dbo.KhoTP_TK where MaSP='" + MaSP1 + "' and LoaiGo='" + cb_LoaiGo_HC.Text + "'";
                cmd.CommandText = TonKho1;
                lb_SLThungTon.Text = cmd.ExecuteScalar().ToString();
            }
            catch(Exception ex)
            {
                MessageBox.Show(ex.Message);
                lb_TonKho_HC.Text = "0";
            }
            finally
            {
                Conn.Close();
                cmd.Dispose();
            }
        }
        private void HieuChinhSL()
        {
            Process prs=new Process();
            SqlConnection Conn = prs.Connect();
            SqlCommand cmd = new SqlCommand();
            cmd.Connection = Conn;
            Conn.Open();
            string Serial1;
            try
            {
                MaSP1 = prs.substring_right(cb_MaSPHC.Text, child);
                string_temp = @"select max(Serial)+1 from dbo.KhoTP_NK";
                cmd.CommandText = string_temp;
                Serial1 = cmd.ExecuteScalar().ToString();
                string_temp = @"select TonKho from dbo.KhoTP_TK where MaSP='" + MaSP1 + "' and LoaiGo='" + cb_LoaiGo_HC.Text + "'";
                cmd.CommandText = string_temp;
                SLNhap_d = double.Parse(cmd.ExecuteScalar().ToString());
                if (SLNhap_d != double.Parse(lb_TonKho_HC.Text))
                    MessageBox.Show("Dữ liệu trong kho đã phát sinh trong lúc bạn hiệu chỉnh, Đóng ứng dụng và làm lại");
                else
                {
                    if (txt_SLThungNhap_HC.Text == "" || txt_SLHC.Text == "")
                        MessageBox.Show("Nhập thiếu thông tin");
                    else
                    {
                        Tong1 = double.Parse(txt_SLHC.Text);
                        SLNhap_d = Tong1 - double.Parse(lb_TonKho_HC.Text);
                        SoThung_d = double.Parse(txt_SLThungNhap_HC.Text) - double.Parse(lb_SLThungTon.Text);

                        string_temp = @"insert into dbo.KhoTP_NK(ChungTu,MaSP,IDNumber,SLNhap,SLThungNhap,LoaiGo,LyDo)Values(0,N'" + MaSP1 + "','" + Serial1 + "'," + SLNhap_d + "," + SoThung_d + ",'"+cb_LoaiGo_HC.Text+"','TPHC')";
                        cmd.CommandText = string_temp;
                        cmd.ExecuteNonQuery();
                        MessageBox.Show("Hiệu chỉnh thành công");
                    }

                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
                MessageBox.Show("Hiệu chỉnh KHÔNG thành công, đã xảy ra lỗi");
            }
            finally
            {
                Conn.Close();
                cmd.Dispose();
            }

        }
        private void bt_edit_HCSL_Click(object sender, EventArgs e)
        {
            HieuChinhSL();
        }
        private void bt_addproduct_Click(object sender, EventArgs e)
        {
            txt_SoCT.Enabled = true;
            txt_SoCT.Text = "";
            MessageBox.Show("Bạn đã kích hoạt chức năng thêm hàng hóa trong một chứng từ có sẵn, Vui lòng nhập số chứng từ");
            txt_SoCT.Focus();
        }
        private void Search_VT()
        {
            Process prs = new Process();
            DataSet ds = new DataSet();
            if (dataGridView10.Rows.Count > 1)
                dataGridView10.Rows.Clear();
            try
            {
                if (cb_MaSP_TKVT.Text == "")
                {
                    if (cb_ViTri_TKVT.Text == "")
                        string_temp = @" SELECT [TenSP],[IDNumber],[LoaiGo] ,[SLNhap] ,[SLThungNhap],[ViTri] FROM [dbo].[KhoTP_SPChuaXuat]";
                    else
                    {

                        string_temp = @"SELECT [TenSP],[IDNumber],[LoaiGo] ,[SLNhap] ,[SLThungNhap],[ViTri] FROM [dbo].[KhoTP_SPChuaXuat] where ViTri='" + cb_ViTri_TKVT.Text + "'";
                    }
                }
                else
                {
                    MaSP1 = prs.substring_right(cb_MaSP_TKVT.Text, child);
                    if (cb_ViTri_TKVT.Text == "")
                        string_temp = @" SELECT [TenSP],[IDNumber],[LoaiGo] ,[SLNhap] ,[SLThungNhap],[ViTri] FROM [dbo].[KhoTP_SPChuaXuat] where MaSP='"+MaSP1+"'";
                    else
                    {

                        string_temp = @"SELECT [TenSP],[IDNumber],[LoaiGo] ,[SLNhap] ,[SLThungNhap],[ViTri] FROM [dbo].[KhoTP_SPChuaXuat] where ViTri='" + cb_ViTri_TKVT.Text + "' and MaSP='"+MaSP1+"'";
                    }
                }
                ds = prs.dts(string_temp);
                for (i = 0; i < ds.Tables[0].Rows.Count; i++)
                {
                    dataGridView10.Rows.Add(ds.Tables[0].Rows[i]["TenSP"].ToString(), ds.Tables[0].Rows[i]["LoaiGo"].ToString(), ds.Tables[0].Rows[i]["SLNhap"].ToString(), ds.Tables[0].Rows[i]["ViTri"].ToString(), ds.Tables[0].Rows[i]["IDNumber"].ToString());
                    dataGridView10.Rows[i].HeaderCell.Value = (i+1).ToString();
                }
                ds.Clear();  
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }

        private void bt_search_VT_Click(object sender, EventArgs e)
        {
            Search_VT();
        }
        private void KiemKe_ViTri()
        {
            Process prs = new Process();
            if (cb_MaSPReport.Text == "")
            {
                string_temp = @"SELECT [MaSP]
                          ,[TenSP]
                          ,[LoaiGo]
                          ,sum([SLNhap]) as SLXuat
                          ,sum([SLThungNhap]) as DBXuat
                          ,COUNT(*) as SoLuong
                          ,[ViTri] as DiaChi
                          ,[Kien] as DVT
                        FROM dbo.[KhoTP_SPChuaXuat]
                        group by [MaSP]
                          ,[TenSP]
                          ,[LoaiGo],[ViTri]
                          ,[Kien]
                          order by ViTri";
            }
            else
            {
                MaSP1 = prs.substring_right(cb_MaSPReport.Text, child);
                if (MaSP1 == "")
                    MessageBox.Show("Kiểm tra lại thông tin sản phẩm ở tab Báo Cáo");
                else
                    string_temp = @"SELECT [MaSP]
                          ,[TenSP]
                          ,[LoaiGo]
                          ,sum([SLNhap]) as SLXuat
                          ,sum([SLThungNhap]) as DBXuat
                          ,COUNT(*) as SoLuong
                          ,[ViTri] as DiaChi
                          ,[Kien] as DVT
                        FROM dbo.[KhoTP_SPChuaXuat]
                        where MaSP like '%"+MaSP1+"%' group by [MaSP],[TenSP],[LoaiGo],[ViTri],[Kien] order by ViTri";
            }
            DataSet ds = prs.dts(string_temp);
            Fr_Report FrR = new Fr_Report();
            //MessageBox.Show(ds.Tables[0].Rows.Count.ToString());
           
            FrR.report_KTPKK(ds);
            FrR.Show();
            ds.Clear();

        }

        private void bt_reset_VT_Click(object sender, EventArgs e)
        {
            txt_Serial_VT.Text = "";
            txt_IDNumberVT.Text = "";
            cb_TenSP_VT.Text = "";
            txt_ViTriVT.Text = "";
            txt_Serial_VT.Enabled = true;
            if (dataGridView8.Rows.Count > 1)
                for (i = dataGridView8.Rows.Count - 2; i >= 0; i--)
                {
                    dataGridView8.Rows.RemoveAt(i);
                }
        }

        private void txt_SoCT_Leave(object sender, EventArgs e)
        {
            if (txt_SoCT.Text == "")
                MessageBox.Show("Số chứng từ cần phải có nếu bạn muốn sử dụng chức năng này");
        }
        

        private void bt_searchQL_Click(object sender, EventArgs e)
        {
            if (txt_ChungTuQL.Text == "")
                MessageBox.Show("Bạn chưa nhập số Chứng Từ");
            else
            {
                Process prs = new Process();
                ChungTu1 = txt_ChungTuQL.Text;
                string_temp = @"SELECT  [Serial],[ChungTu],Load_cbSP.TenSP,Load_cbSP.MaSP,[ArticleNumber],[IDNumber],[SoHD],[KhachHang],[LoaiGo],[DVGC],[SoBB],[SLXuat],[SLThungXuat],[DVT],convert(varchar(10),[Ngay],103) as Ngay,[ViTri],[NgayInsert],[GhiChu],[LyDo]
                                FROM [dbo].[KhoTP_XK] inner join dbo.Load_cbSP on Load_cbSP.MaSP=KhoTP_XK.MaSP where ChungTu='" + ChungTu1 + "'";
                DataSet ds = new DataSet();
                try
                {

                    ds = prs.dts(string_temp);
                    if (dataGridView11.Rows.Count > 1)
                        dataGridView11.Rows.Clear();
                    lb_TongQLKho.Text = "0";
                    for (i = 0; i < ds.Tables[0].Rows.Count; i++)
                    {
                        MaSP1 = ds.Tables[0].Rows[i]["MaSP"].ToString();
                        TenSP1 = ds.Tables[0].Rows[i]["TenSP"].ToString();
                        LoaiGo1 = ds.Tables[0].Rows[i]["LoaiGo"].ToString();
                        SLNhap1 = ds.Tables[0].Rows[i]["SLXuat"].ToString();
                        DVT1 = ds.Tables[0].Rows[i]["DVT"].ToString();
                        SoThung1 = ds.Tables[0].Rows[i]["SLThungXuat"].ToString();
                        ArticleNumber1 = ds.Tables[0].Rows[i]["ArticleNumber"].ToString();
                        IDNumber1 = ds.Tables[0].Rows[i]["IDNumber"].ToString();
                        ViTri1 = ds.Tables[0].Rows[i]["ViTri"].ToString();
                        SoBB1 = ds.Tables[0].Rows[i]["SoBB"].ToString();
                        DVGC1 = ds.Tables[0].Rows[i]["DVGC"].ToString();
                        GhiChu1 = ds.Tables[0].Rows[i]["GhiChu"].ToString();
                        Ngay1 = ds.Tables[0].Rows[i]["Ngay"].ToString();
                        NgayInsert1 = ds.Tables[0].Rows[i]["NgayInsert"].ToString();
                        LyDo1 = ds.Tables[0].Rows[i]["LyDo"].ToString();
                        KhachHang1 = ds.Tables[0].Rows[i]["KhachHang"].ToString();
                        SoHD1 = ds.Tables[0].Rows[i]["SoHD"].ToString();
                        string_temp = ds.Tables[0].Rows[i]["Serial"].ToString();
                        dataGridView11.Rows.Add(false, MaSP1, TenSP1, LoaiGo1, SLNhap1, DVT1, SoThung1, ArticleNumber1, IDNumber1, ViTri1, LyDo1, KhachHang1, Ngay1, SoBB1, DVGC1, SoHD1, NgayInsert1, GhiChu1,string_temp);


                    }
                    prs.formatcolordatagrid(dataGridView11);

                }
                catch (Exception ex)
                {
                    MessageBox.Show(ex.Message);
                }
            }

        }

        private void bt_listQLKho_Click(object sender, EventArgs e)
        {
            for (i = dataGridView11.Rows.Count - 2; i >= 0; i--)
            {
                check = dataGridView11.Rows[i].Cells["CheckboxQLKho"].Value.ToString();

                if (check == "1" || check == "True")
                {
                    Tong1 += double.Parse(dataGridView11.Rows[i].Cells["SLQLKho"].Value.ToString());
                }
                if (check == "0" || check == "False")
                {

                    dataGridView11.Rows.RemoveAt(i);
                }
            }
            bt_deleteDSHH.Enabled = true;
        }

        private void dataGridView11_CurrentCellDirtyStateChanged(object sender, EventArgs e)
        {
            if (dataGridView11.IsCurrentCellDirty)
                dataGridView11.CommitEdit(DataGridViewDataErrorContexts.Commit);
        }

        private void dataGridView11_CellValueChanged(object sender, DataGridViewCellEventArgs e)
        {
            try
            {

                if (e.ColumnIndex == 0) //compare to checkBox column index
                {
                    DataGridViewCheckBoxCell chk = (DataGridViewCheckBoxCell)dataGridView11[e.ColumnIndex, e.RowIndex];
                    //check = dataGridView11.Rows[e.RowIndex].Cells["ViTriQLKho"].Value.ToString();

                    if (!DBNull.Value.Equals(chk.Value) && chk.Value == chk.TrueValue)
                    {
                        //cb_ViTrioutput.Text = check;
                        Tong1 = double.Parse(lb_TongQLKho.Text);
                        Tong1 += double.Parse(dataGridView11.Rows[e.RowIndex].Cells["SLQLKho"].Value.ToString());

                        if (Tong1 != 0)
                            lb_TongQLKho.Text = string.Format("{0:###,###.##}", Tong1);
                        else
                            lb_TongQLKho.Text = "0";
                    }
                    else
                    {
                        //cb_ViTriinput.Text = check;
                        Tong1 = double.Parse(lb_TongQLKho.Text);
                        Tong1 -= double.Parse(dataGridView11.Rows[e.RowIndex].Cells["SLQLKho"].Value.ToString());
                        if (Tong1 != 0)
                            lb_TongQLKho.Text = string.Format("{0:###,###.##}", Tong1);
                        else
                            lb_TongQLKho.Text = "0";
                    }
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }

        private void bt_deleteDSHH_Click(object sender, EventArgs e)
        {
            Data dta = new Data();
            SqlConnection Conn = dta.Connect();
            Conn.Open();
            SqlCommand cmd = new SqlCommand();
            cmd.Connection = Conn;
            cmd.CommandType = CommandType.StoredProcedure;
            cmd.CommandText = "Tran_Del_Up_XKTP";
            DialogResult d = MessageBox.Show("Bạn có chắc muốn xóa tất cả các hàng hóa ở danh sách phía dưới " , "Thông Báo", MessageBoxButtons.OKCancel);
            if (d == DialogResult.OK)
            {
                try
                {


                    for (i = dataGridView11.Rows.Count - 2; i >= 0; i--)
                    {

                        string_temp = dataGridView11.Rows[i].Cells["Serial_QLKho"].Value.ToString();
                        ViTri1 = dataGridView11.Rows[i].Cells["ViTriQLKho"].Value.ToString();
                        cmd.Parameters.AddWithValue("@Serial", string_temp);
                        cmd.Parameters.AddWithValue("@ViTri", ViTri1);
                        cmd.ExecuteNonQuery();
                        cmd.Parameters.Clear();
                        dataGridView11.Rows.RemoveAt(i);

                    }
                    MessageBox.Show("Dữ liệu được xóa thành công");

                }
                catch (Exception ex)
                {
                    MessageBox.Show("Đã xảy ra lỗi khi xóa dữ liệu, vui lòng kiểm tra lại");
                    MessageBox.Show(ex.Message);
                }
                finally
                {
                    Conn.Close();
                    cmd.Dispose();
                }
            }
        }

        private void bt_XacNhanXK_Click(object sender, EventArgs e)
        {
            Data dta = new Data();
            SqlConnection Conn = dta.Connect();
            Conn.Open();
            SqlCommand cmd = new SqlCommand();
            cmd.Connection = Conn;
            
            cmd.CommandText = @"UPDATE [dbo].[KhoTP_ChungTu] SET 
                                [Checked] =1 WHERE MaCT="+txt_ChungTuQL.Text;
           
            DialogResult d = MessageBox.Show("Bạn muốn xác nhận xuất hàng cho chứng từ "+txt_ChungTuQL.Text, "Thông Báo", MessageBoxButtons.OKCancel);
            if (d == DialogResult.OK)
            {
                try
                {
                    cmd.ExecuteNonQuery();
                    MessageBox.Show("Xác nhận thành công");
                    dataGridView11.Rows.Clear();

                }
                catch (Exception ex)
                {
                    MessageBox.Show("Đã xảy ra lỗi, vui lòng kiểm tra lại");
                    MessageBox.Show(ex.Message);
                }
                finally
                {
                    Conn.Close();
                    cmd.Dispose();
                }
            }
        }

        private void rd_NhapXuatThang_CheckedChanged(object sender, EventArgs e)
        {
            lb_NgayBegin.Text = "Từ Tháng";
            lb_NgayEnd.Text = "Đến Tháng";
            txt_Nam.Visible = true;
            lb_Nam.Visible = true;
            txt_NgayBegin.Text = "";
            txt_NgayEnd.Text = "";
            chk_statistic.Visible = false;
        }

        private void tab_QLKho_Click(object sender, EventArgs e)
        {
            txt_ChungTuQL.Items.Clear();
            Data dta = new Data();
            FormProcess Frp = new FormProcess();
            string sql_load = @"select distinct(MaCT) from dbo.KhoTP_ChungTu inner join KhoTP_XK on KhoTP_XK.ChungTu=KhoTP_ChungTu.MaCT where Checked='0'";
            SqlConnection Conn = dta.Connect();
            SqlCommand cmd = new SqlCommand();
            
            Conn.Open();
            cmd.Connection = Conn;
            cmd.CommandText = sql_load;
            try
            {
                SqlDataReader rd = cmd.ExecuteReader();
                while (rd.Read())
                {
                    txt_ChungTuQL.Items.Add(rd[0].ToString());
                }
                rd.Dispose();
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
            finally
            {
                Conn.Close();
                cmd.Dispose();
            }
        }

        private void tab_BangKe_Click(object sender, EventArgs e)
        {
            Data dta = new Data();
            SqlConnection Conn = dta.Connect();
            Conn.Open();
            /*SqlCommand cmd = new SqlCommand();
            cmd.Connection = Conn;

            cmd.CommandText = @"select CONVERT(nvarchar(10),getdate(),101)";*/
            try
            {
                string[] temp = txt_NgayBK.Text.Split('/');
                string_temp = temp[1] + "/" + temp[0] + "/" + temp[2];
                
                //string_temp = cmd.ExecuteScalar().ToString();
                string_temp = @"select qry1.Serial,dbo.KhoTP_ChungTu.MaCT as ChungTu,dbo.Load_cbSP.MaSP ,dbo.Load_cbSP.TenSP,[ArticleNumber],[IDNumber],dbo.KhoTP_ChungTu.[SoHD]
                      ,[KhachHang],[LoaiGo],[DVGC],dbo.KhoTP_ChungTu.[SoBB],SoLuong,SLThung,[DVT],[NgayCT],NgayInsert,[ViTri],[GhiChu],[LyDo],qry1.flag from (SELECT [Serial]
                      ,[ChungTu],[MaSP],[ArticleNumber],[IDNumber],[SoHD],[KhachHang],[LoaiGo],[DVGC] ,[SoBB],[SLNhap] as SoLuong,[SLThungNhap] as SLThung,[DVT]
                      ,convert(varchar(10),[Ngay],103) as NgayCT
                      ,NgayInsert,[ViTri],[GhiChu],[LyDo],flag=1
                  FROM [dbo].[KhoTP_NK]
                  union all
                  SELECT [Serial],[ChungTu],[MaSP],[ArticleNumber],[IDNumber],[SoHD],[KhachHang],[LoaiGo] ,[DVGC] ,[SoBB],[SLXuat] as SoLuong,[SLThungXuat] as SLThung
                      ,[DVT],convert(varchar(10),[Ngay],103) as NgayCT,NgayInsert,[ViTri],[GhiChu],[LyDo],flag=0
                  FROM [dbo].[KhoTP_XK]) as qry1 inner join dbo.Load_cbSP on qry1.MaSP=dbo.Load_cbSP.MaSP inner join dbo.KhoTP_ChungTu on KhoTP_ChungTu.MaCT=qry1.ChungTu
                  where NgayInsert>='" + string_temp+" 00:00:00' and NgayInsert<='"+string_temp+" 23:59:59' order by NgayInsert";
                DataSet ds = dta.dts(string_temp);
                dataGridViewX1.DataSource = ds.Tables[0];
                for (i = dataGridViewX1.Rows.Count - 2; i >= 0; i--)
                {
                    if (dataGridViewX1.Rows[i].Cells["flag_BK"].Value.ToString() == "1")
                        dataGridViewX1.Rows[i].DefaultCellStyle.BackColor = Color.AliceBlue;
                     if(dataGridViewX1.Rows[i].Cells["flag_BK"].Value.ToString()=="0")
                         dataGridViewX1.Rows[i].DefaultCellStyle.BackColor = Color.Silver;
                }
                temp.Clone();

            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);

            }
            finally
            {
                Conn.Close();
                //cmd.Dispose();
            }
        }

        private void dataGridView9_Click(object sender, EventArgs e)
        {
            try
            {
                
                int r = dataGridView9.CurrentCell.RowIndex;


                j = dataGridView9.CurrentCell.ColumnIndex;
                if (j == 1)
                {
                    if (dataGridView10.Rows.Count > 1)
                        dataGridView10.Rows.Clear();
                    string_temp = dataGridView9.Rows[r].Cells["ViTri_TK"].Value.ToString();
                    cb_ViTri_TKVT.Text = string_temp;
                    Search_VT();
                }
            }
            catch (Exception ex)
            { MessageBox.Show(ex.Message); }
        }

        private void lnk_Fifo_Click(object sender, EventArgs e)
        {
            if (cb_KhachHangoutput.Text == "" || cb_LyDoXuat.Text == "" || txt_SoHDoutput.Text == "" || cb_MaSPoutput.Text == ""||txt_SLoutput.Text=="")
                MessageBox.Show("Bạn cần nhập đầy đủ Tên SP,Ngày, Khách Hàng, Hợp Đồng,Lý Do Xuất và Số Lượng");
            else
            {
                Tong1 = 0;
                Process prs = new Process();
                MaSP1 = prs.substring_right(cb_MaSPoutput.Text, child);
                string_temp = @"select * from KhoTP_SPChuaXuat where MaSP='" + MaSP1 + "' order by Ngay,ViTri";
                Pallet_d = 0;
                Topfiller_d = 0;
                Sidefiller_d = 0;
                other_d = 0;
                DataSet ds = new DataSet();
                try
                {
                   
                    ds = prs.dts(string_temp);
                    if (dataGridView3.Rows.Count > 1)
                        dataGridView3.Rows.Clear();
                    Ngay1 = txt_Ngayoutput.Text;
                    string[] temp = txt_Ngayoutput.Text.Split('/');
                    NgayInsert1 = temp[1] + "/" + temp[0] + "/" + temp[2];
                    LyDo1 = prs.substring_right(cb_LyDoXuat.Text, child);
                    KhachHang1 = cb_KhachHangoutput.Text;
                    SoHD1 = txt_SoHDoutput.Text;
                    SoBB1 = txt_SoBBoutput.Text;
                    SLXuat_d = double.Parse(txt_SLoutput.Text);
                    double Pallet1=0,Topfiller1=0,Sidefiller1=0,other1=0;
                    Pallet1=double.Parse(txt_pallet.Text);
                    Topfiller1=double.Parse(txt_topfiller.Text);
                    Sidefiller1=double.Parse(txt_sidefiller.Text);
                    other1=double.Parse(txt_other.Text);
                    for (i = 0; i < ds.Tables[0].Rows.Count; i++)
                    {
                        MaSP1 = ds.Tables[0].Rows[i]["MaSP"].ToString();
                        TenSP1 = ds.Tables[0].Rows[i]["TenSP"].ToString();
                        LoaiGo1 = ds.Tables[0].Rows[i]["LoaiGo"].ToString();
                        SLNhap1 = ds.Tables[0].Rows[i]["SLNhap"].ToString();
                        DVT1 = ds.Tables[0].Rows[i]["DVT"].ToString();
                        SoThung1 = ds.Tables[0].Rows[i]["SLThungNhap"].ToString();
                        ArticleNumber1 = ds.Tables[0].Rows[i]["ArticleNumber"].ToString();
                        IDNumber1 = ds.Tables[0].Rows[i]["IDNumber"].ToString();
                        ViTri1 = ds.Tables[0].Rows[i]["ViTri"].ToString();
                        //SoBB1 = ds.Tables[0].Rows[i]["SoBB"].ToString();
                        DVGC1 = ds.Tables[0].Rows[i]["DVGC"].ToString();
                        Kien1 = ds.Tables[0].Rows[i]["Kien"].ToString();
                        GhiChu1 = txt_GhiChuoutput.Text;
                        if (Kien1 == "Pallet")
                        {
                            Pallet_d++;
                            Tong1 += double.Parse(SLNhap1);
                            if (Tong1 <= SLXuat_d)
                            {
                                if (Pallet_d <= Pallet1)
                                {
                                    dataGridView3.Rows.Add(true, MaSP1, TenSP1, LoaiGo1, SLNhap1, DVT1, SoThung1, ArticleNumber1, IDNumber1, ViTri1, LyDo1, KhachHang1, Kien1, Ngay1, SoBB1, DVGC1, SoHD1, NgayInsert1, GhiChu1);
                                }
                                else
                                    Tong1 -= double.Parse(SLNhap1);
                            }
                            else
                            {
                                Tong1 = Tong1 - double.Parse(SLNhap1);
                                break;
                            }

                        }
                        if (Kien1 == "TopFiller")
                        {
                            Topfiller_d++;
                            Tong1 += double.Parse(SLNhap1);
                            if (Tong1 <= SLXuat_d)
                            {
                                if (Topfiller_d <= Topfiller1)
                                    dataGridView3.Rows.Add(true, MaSP1, TenSP1, LoaiGo1, SLNhap1, DVT1, SoThung1, ArticleNumber1, IDNumber1, ViTri1, LyDo1, KhachHang1, Kien1, Ngay1, SoBB1, DVGC1, SoHD1, NgayInsert1, GhiChu1);
                                else
                                    Tong1 -= double.Parse(SLNhap1);
                            }
                            else
                            {
                                Tong1 = Tong1 - double.Parse(SLNhap1);
                                break;
                            }
                        }
                        if(Kien1=="SideFiller")
                        {
                            Sidefiller_d++;
                            Tong1 += double.Parse(SLNhap1);
                             if (Tong1 <= SLXuat_d)
                             {
                                 if (Sidefiller_d <= Sidefiller1)
                                    dataGridView3.Rows.Add(true, MaSP1, TenSP1, LoaiGo1, SLNhap1, DVT1, SoThung1, ArticleNumber1, IDNumber1, ViTri1, LyDo1, KhachHang1, Kien1, Ngay1, SoBB1, DVGC1, SoHD1, NgayInsert1, GhiChu1);
                                 else
                                     Tong1 -= double.Parse(SLNhap1);
                             }
                             else
                             {
                                 Tong1 = Tong1 - double.Parse(SLNhap1);
                                 break;
                             }
                        }
                        if (Kien1 == "Piece")
                        {
                            other_d++;
                            Tong1 += double.Parse(SLNhap1);
                            if (Tong1 <= SLXuat_d)
                            {
                                if (other_d <= other1)
                                    dataGridView3.Rows.Add(true, MaSP1, TenSP1, LoaiGo1, SLNhap1, DVT1, SoThung1, ArticleNumber1, IDNumber1, ViTri1, LyDo1, KhachHang1, Kien1, Ngay1, SoBB1, DVGC1, SoHD1, NgayInsert1, GhiChu1);
                                else
                                    Tong1 -= double.Parse(SLNhap1);
                            }
                            else
                            {
                                Tong1 = Tong1 - double.Parse(SLNhap1);
                                break;
                            }
                        } 
                    }
                    if (Tong1 != 0)
                        lb_TongXuat.Text = string.Format("{0:###,###.##}", Tong1);
                    else
                        lb_TongXuat.Text = "0";
                    prs.formatcolordatagrid(dataGridView3);
                    temp.Clone();
                }
                catch (Exception ex)
                {
                    MessageBox.Show(ex.Message);
                }
            }
          
            
        }

        private void txt_SLinput_Leave(object sender, EventArgs e)
        {
            Process prs = new Process();
            try
            {
                //MaSP1 = prs.substring_right(cb_MaSPinput.Text, child);
                check = txt_ArticleNumberinput.Text.Trim();
                SLNhap1 = txt_SLinput.Text;
                for (i = 0; i < dataGridView7.Rows.Count - 1; i++)
                {

                    string_temp = dataGridView7.Rows[i].Cells["ArticleNumber"].Value.ToString();
                    if (sosanh(check, string_temp))
                    {
                        if (SLNhap1 == dataGridView7.Rows[i].Cells["SLuong"].Value.ToString())
                        {
                            cb_Kieninput.Text="Pallet";
                        }
                        if (SLNhap1 == dataGridView7.Rows[i].Cells["TopFilller"].Value.ToString())
                        {
                            cb_Kieninput.Text="TopFiller";
                        }

                        if(SLNhap1 == dataGridView7.Rows[i].Cells["Other"].Value.ToString())
                        {
                            cb_Kieninput.Text="Piece";
                        }
                        if(SLNhap1==dataGridView7.Rows[i].Cells["SideFiller"].Value.ToString())
                        {
                            cb_Kieninput.Text = "SideFiller";
                        }
                        
                        break;
                    }
                }

                if (i == dataGridView7.Rows.Count - 1)
                {
                    MessageBox.Show("Mã vạch không đúng");
                    txt_ArticleNumberinput.Text = "";
                    txt_ArticleNumberinput.Focus();
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }

        private void cb_KieuXuat_SelectedIndexChanged(object sender, EventArgs e)
        {
            Process prs=new Process();
            if (cb_KieuXuat.Text == "Chuẩn")
            {
                //MessageBox.Show("aaa");
                if (cb_MaSPoutput.Text != "")
                {
                    MaSP1 = cb_MaSPoutput.Text.Trim();
                  
                        for (i = 0; i < dataGridView7.Rows.Count - 1; i++)
                        {
                            if (MaSP1 == dataGridView7.Rows[i].Cells["MaSP"].Value.ToString())
                            {
                                txt_pallet.Text = dataGridView7.Rows[i].Cells["SLPallet"].Value.ToString();


                                txt_topfiller.Text = dataGridView7.Rows[i].Cells["SLTopfiller"].Value.ToString();


                                txt_other.Text = dataGridView7.Rows[i].Cells["SLOther"].Value.ToString();

                                txt_sidefiller.Text = dataGridView7.Rows[i].Cells["SLSidefiller"].Value.ToString();
                                break;
                            }
                        }
                }
            }
            else
            {
                txt_pallet.Text = "";
                txt_sidefiller.Text = "";
                txt_other.Text = "";
                txt_topfiller.Text = "";
            }

        }

        private void txt_SLChuaHC_Leave(object sender, EventArgs e)
        {
            checktext_number(txt_SLChuaHC);
        }

        private void bt_SLChua_Click(object sender, EventArgs e)
        {
            Process prs = new Process();
            //string_temp = @"select SLToiDa from dbo.KhoTP_MatBangKho where ViTri='" + cb_ViTriHCVT.Text.Trim() + "'";
            SqlConnection Conn = prs.Connect();
            SqlCommand cmd = new SqlCommand();
            Conn.Open();
            cmd.Connection = Conn;
            try
            {
                MaSP1 = prs.substring_right(cb_MaSPHCVT.Text, child);
                if (cb_ViTriHCVT.Text == "" || MaSP1 == "" || txt_SLChuaHC.Text == "")
                    MessageBox.Show("Nhập đầy đủ thông tin trước khi chỉnh sửa");
                else
                {
                    check_number = int.Parse(txt_SLChuaHC.Text) - int.Parse(lb_SLChua.Text);
                    string_temp = @"UPDATE [dbo].[KhoTP_MatBangKho] SET [SLToiDa] ="+txt_SLChuaHC.Text+ ",[SLTheoDoi] =SLTheoDoi +"+check_number+" ,[MaSP] = '"+MaSP1+"' WHERE ViTri='"+cb_ViTriHCVT.Text+"'";
                    cmd.CommandText = string_temp;
                    cmd.ExecuteNonQuery();
                    MessageBox.Show("Chỉnh sửa thành công");
                    cb_MaSPHCVT.Text = "";
                    cb_ViTriHCVT.Text = "";
                    txt_SLChuaHC.Text = "";
                }
                
                
            }
            catch (Exception ex)
            {
                MessageBox.Show("Đã xảy ra lỗi, Hiệu chỉnh KHÔNG thành công",ex.Message);
                lb_SLChua.Text = "0";
            }
            finally
            {
                Conn.Close();
                cmd.Dispose();
            }

        }

        private void cb_ViTriHCVT_SelectedIndexChanged(object sender, EventArgs e)
        {
            Data dta = new Data();
            
            string_temp = @"select SLToiDa from dbo.KhoTP_MatBangKho where ViTri='"+cb_ViTriHCVT.Text.Trim()+"'";
            SqlConnection Conn = dta.Connect();
            SqlCommand cmd = new SqlCommand();
            Conn.Open();
            cmd.Connection = Conn;
            try
            {
                cmd.CommandText = string_temp;
                lb_SLChua.Text = cmd.ExecuteScalar().ToString();
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
            finally
            {
                Conn.Close();
                cmd.Dispose();
            }
        }

        private void Search_VitriChuyen()
        {
            Process prs = new Process();
            DataSet ds = new DataSet();
            string_temp = @"SELECT     dbo.KhoTP_NK.Serial, dbo.KhoTP_NK.IDNumber, dbo.Load_cbSP.MaSP,dbo.Load_cbSP.TenSP, dbo.KhoTP_NK.SLNhap, convert(varchar(10),dbo.KhoTP_NK.Ngay,103) as NgayInsert,dbo.KhoTP_NK.Ngay, dbo.KhoTP_NK.ViTri,Kien
                            FROM         dbo.KhoTP_NK  LEFT OUTER JOIN
                      dbo.KhoTP_XK ON dbo.KhoTP_NK.IDNumber = dbo.KhoTP_XK.IDNumber inner join dbo.Load_cbSP on Load_cbSP.MaSP=dbo.KhoTP_NK.MaSP where dbo.KhoTP_XK.IDNumber IS NULL";
            try
            {
                if (dataGridView12.Rows.Count > 1)
                    dataGridView12.Rows.Clear();
                if (dataGridView13.Rows.Count > 1)
                    dataGridView13.Rows.Clear();
                if (cb_VTSA.Text != ""&&cb_VTSB.Text!="")
                {
                    
                    if (cb_MaSP_VTS.Text != "")
                    {
                        MaSP1 = prs.substring_right(cb_MaSP_VTS.Text, child);
                        if (MaSP1 == "")
                            MessageBox.Show("Nhập sai thông tin Sản Phẩm");
                        else
                        {
                            string_temp += " and dbo.Load_cbSP.MaSP='" + MaSP1 + "' and dbo.KhoTP_NK.ViTri='" + cb_VTSA.Text + "'";
                        }
                        ds = prs.dts(string_temp);
                        
                        if (ds.Tables[0].Rows.Count > 0)
                        {
                            for (i = 0; i < ds.Tables[0].Rows.Count; i++)
                            {
                                dataGridView13.Rows.Add(false, ds.Tables[0].Rows[i]["MaSP"].ToString(), ds.Tables[0].Rows[i]["TenSP"].ToString(), ds.Tables[0].Rows[i]["ViTri"].ToString(), ds.Tables[0].Rows[i]["SLNhap"].ToString(), ds.Tables[0].Rows[i]["IDNumber"].ToString(), ds.Tables[0].Rows[i]["Serial"].ToString(), ds.Tables[0].Rows[i]["NgayInsert"].ToString(), ds.Tables[0].Rows[i]["Kien"].ToString());
                            }
                           
                        }
                        else
                            MessageBox.Show("Không có dữ liệu, vui lòng kiểm tra lại thông tin tìm kiếm");
                        ds.Clear();
                    }
                }
                //MessageBox.Show(string_temp);
               
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }

        private void bt_Search_VTS_Click(object sender, EventArgs e)
        {
            Search_VitriChuyen();
        }

        private void ViTri_edit_s()
        {
            Process prs = new Process();
            SqlConnection Conn = prs.Connect();
            SqlCommand cmd = new SqlCommand();
            Conn.Open();
            cmd.Connection = Conn;
            cmd.CommandType = CommandType.StoredProcedure;
            cmd.CommandText = "Upd_KTPVT";
            string VitriA = null, ViTriB = null,Serial1=null;
                try
                {
                    DialogResult d = MessageBox.Show("Tất cả những Pallet trong danh sách sẽ được chuyển qua vị trí "+cb_VTSB.Text,"Thông Báo", MessageBoxButtons.OKCancel);

                    if (d == DialogResult.OK)
                    {
                        for (i = dataGridView12.Rows.Count-2; i>=0; i--)
                        {
                            VitriA = dataGridView12.Rows[i].Cells["ViTri_VTSA"].Value.ToString();
                            ViTriB = dataGridView12.Rows[i].Cells["ViTri_VTSB"].Value.ToString();
                            Serial1=dataGridView12.Rows[i].Cells["Serial_VTS"].Value.ToString();
                            cmd.Parameters.AddWithValue("@Serial", Serial1);
                            cmd.Parameters.AddWithValue("@ViTri1", VitriA);
                            cmd.Parameters.AddWithValue("@ViTri2", ViTriB);

                            cmd.ExecuteNonQuery();

                            cmd.Parameters.Clear();
                            dataGridView12.Rows.RemoveAt(i);
                           
                        }
                        MessageBox.Show("Chuyển thành công");
                        

                    }
                }
                catch (Exception ex)
                {
                    MessageBox.Show(ex.Message);
                    MessageBox.Show("Đã xảy ra lỗi, không chuyển được");
                }
                finally
                {
                    Conn.Close();
                    cmd.Dispose();
                }
            
        }

        private void bt_Chuyen_VTS_Click(object sender, EventArgs e)
        {
            ViTri_edit_s();
        }

        private void bt_ChuyenPallets_Click(object sender, EventArgs e)
        {
            if (cb_VTSB.Text != "")
            {
                if (dataGridView13.Rows.Count > 1)
                {
                    for (i = dataGridView13.Rows.Count - 2; i >= 0; i--)
                    {
                        check = dataGridView13.Rows[i].Cells["chk_pallets"].Value.ToString();

                        if (check == "1" || check == "True")
                        {
                            dataGridView12.Rows.Add(dataGridView13.Rows[i].Cells["MaSP_VTSA"].Value.ToString(), dataGridView13.Rows[i].Cells["TenSP_VTSA"].Value.ToString(), dataGridView13.Rows[i].Cells["SoLuong_VTSA"].Value.ToString(), dataGridView13.Rows[i].Cells["IDNumber_VTSA"].Value.ToString(), dataGridView13.Rows[i].Cells["ViTriA_VTSA"].Value.ToString(), cb_VTSB.Text.Trim(), dataGridView13.Rows[i].Cells["Serial_VTSA"].Value.ToString(), dataGridView13.Rows[i].Cells["Ngay_VTSA"].Value.ToString());
                        }
                        dataGridView13.Rows.RemoveAt(i);
                    }
                }
            }
        }

        private void bt_closeout_Click(object sender, EventArgs e)
        {
            string[] temp = txt_NgayBK.Text.Split('/');
            NgayInsert1 = temp[1] + "/" + temp[0] + "/" + temp[2];
            Process prs = new Process();
            SqlConnection Conn = new SqlConnection();
            SqlCommand cmd = new SqlCommand();
            Conn = prs.Connect();
            Conn.Open();
            cmd.Connection = Conn;
            try
            {
                cmd.CommandText = "INSERT INTO [dbo].[closeout]([NgayDongKy],[KhuVuc]) VALUES ('" + NgayInsert1 + "','KhoTP')";
                cmd.ExecuteNonQuery();
                MessageBox.Show("Khóa sổ cho ngày "+txt_NgayBK.Text+" thành công");
                cb_Closeout.Items.Add(txt_NgayBK.Text);
                bt_closeout.Visible = false;
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
            finally
            {
                Conn.Close();
                cmd.Dispose();
            }
        }
        private void ThongTin()
        {
            
            string_temp = @"select * from KhoTP_ThongTin";
            DataSet ds = new DataSet();
            Process prs = new Process();
     
            try
            {
                ds = prs.dts(string_temp);
                if (ds.Tables[0].Rows.Count > 0)
                {
                    string_temp="";
                    for (i = 0; i < ds.Tables[0].Rows.Count; i++)
                    {
                        string_temp += ds.Tables[0].Rows[i]["MaSP"].ToString() + " còn " + ds.Tables[0].Rows[i]["SoLuong"].ToString() + " ; ";
                    }
                    lb_GhiNo.Text = string_temp;
                    ds.Clear();
                }
            }
            catch(Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }

        private void lik_ThongTin_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
        {
            ThongTin();
        }

        private void date_default_CheckedChanged(object sender, EventArgs e)
        {
            Process prs=new Process();
            SqlConnection Conn = prs.Connect();
            SqlCommand cmd = new SqlCommand();
            Conn.Open();
            cmd.Connection = Conn;
            try
            {
                if (date_default.Checked == true)
                {
                    cmd.CommandText = "Select convert(char(10), getdate(), 103)";
                    lb_Date_input.Text = cmd.ExecuteScalar().ToString();
                    string[] temp = lb_Date_input.Text.Split('/');
                    txt_Ngayinput.Text = temp[1] + "/" + temp[0] + "/" + temp[2];
                    txt_Ngayinput.Enabled = false;
                }
                if (date_default.Checked == false)
                {
                    txt_Ngayinput.Enabled = true;
                }

            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
            finally
            {
                Conn.Close();
                cmd.Dispose();
            }
        }
        #region //Tab Hieu Chinh
        private void dataGridView14_CurrentCellDirtyStateChanged(object sender, EventArgs e)
        {
            if (dataGridView14.IsCurrentCellDirty)
                dataGridView14.CommitEdit(DataGridViewDataErrorContexts.Commit);
        }

        private void dataGridView14_CellValueChanged(object sender, DataGridViewCellEventArgs e)
        {
            try
            {

                if (e.ColumnIndex == 0) //compare to checkBox column index
                {
                    DataGridViewCheckBoxCell chk = (DataGridViewCheckBoxCell)dataGridView14[e.ColumnIndex, e.RowIndex];
                    //check = dataGridView14.Rows[e.RowIndex].Cells["ViTrioutput"].Value.ToString();

                    if (!DBNull.Value.Equals(chk.Value) && chk.Value == chk.TrueValue)
                    {
                        //cb_ViTrioutput.Text = check;
                        Tong1 = double.Parse(lb_Tong_Editinput.Text);
                        Tong1 += double.Parse(dataGridView14.Rows[e.RowIndex].Cells["SLNhap_Editinput"].Value.ToString());

                        if (Tong1 != 0)
                            lb_Tong_Editinput.Text = string.Format("{0:###,###.##}", Tong1);
                        else
                            lb_TongXuat.Text = "0";
                    }
                    else
                    {
                       // cb_ViTriinput.Text = check;
                        Tong1 = double.Parse(lb_Tong_Editinput.Text);
                        Tong1 -= double.Parse(dataGridView14.Rows[e.RowIndex].Cells["SLNhap_Editinput"].Value.ToString());
                        if (Tong1 != 0)
                            lb_Tong_Editinput.Text = string.Format("{0:###,###.##}", Tong1);
                        else
                            lb_Tong_Editinput.Text = "0";
                    }
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }

        private void bt_Load_Editinput_Click(object sender, EventArgs e)
        {
            Process prs = new Process();
           // SqlConnection Conn = prs.Connect();
            DataSet ds = new DataSet();
            //Conn.Open();
            try
            {
                if (cb_MaSP_Editinput.Text == "" || cb_LyDo_Editinput.Text == "")
                    MessageBox.Show("Bạn cần nhập lý do muốn chuyển");
                else
                {
                    if (dataGridView14.Rows.Count > 1)
                        dataGridView14.Rows.Clear();
                    MaSP1 = prs.substring_right(cb_MaSP_Editinput.Text, child);
                    LyDo1 = prs.substring_right(cb_LyDo_Editinput.Text, child);
                    if (MaSP1 == "" || LyDo1 == "")
                        MessageBox.Show("Nhập sai thông tin");
                    else
                    {
                        string[] temp =dtp_Ngay_Editinput.Text.Split('/');
                        Ngay_start1 = temp[1] + "/" + temp[0] + "/" + temp[2];
                        string_temp = @"SELECT dbo.Load_cbSP.MaSP,dbo.Load_cbSP.TenSP,[ArticleNumber],[IDNumber] ,[SLNhap],convert(varchar(10),[Ngay],103) as Ngay,[ViTri] ,[NgayInsert],LyDo
                                            FROM [dbo].[KhoTP_NK] inner join dbo.Load_cbSP on (dbo.Load_cbSP.MaSP=KhoTP_NK.MaSP and dbo.Load_cbSP.MaSP='"+MaSP1+"') where Ngay>='"+Ngay_start1+" 00:00' and Ngay<='"+Ngay_start1+" 23:59'";
                        ds = prs.dts(string_temp);
                        if (ds.Tables[0].Rows.Count > 0)
                        {
                            for (i = 0; i < ds.Tables[0].Rows.Count; i++)
                            {
                                dataGridView14.Rows.Add(false, ds.Tables[0].Rows[i]["MaSP"].ToString(), ds.Tables[0].Rows[i]["TenSP"].ToString(), ds.Tables[0].Rows[i]["SLNhap"].ToString(), ds.Tables[0].Rows[i]["ArticleNumber"].ToString(), ds.Tables[0].Rows[i]["IDNumber"].ToString(), ds.Tables[0].Rows[i]["LyDo"].ToString(), LyDo1, ds.Tables[0].Rows[i]["ViTri"].ToString(), ds.Tables[0].Rows[i]["Ngay"].ToString(), ds.Tables[0].Rows[i]["NgayInsert"].ToString());
                            }
                            lb_Tong_Editinput.Text = "0";
                            prs.formatcolordatagrid(dataGridView14);
                           
                        }
                        else
                            MessageBox.Show("Không có dữ liệu");
                    }
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
            finally
            {
                //Conn.Close();
                ds.Clear(); 
            }
        }
        private void bt_Edit_Editinput_Click(object sender, EventArgs e)
        {
            Process prs = new Process();
            SqlConnection Conn = prs.Connect();
            Conn.Open();
            SqlCommand cmd = new SqlCommand();
            cmd.Connection = Conn;

            try
            {
                DialogResult d = MessageBox.Show("Tất cả những thông tin trong danh sách sẽ được chuyển qua lý do " + cb_LyDo_Editinput.Text, "Thông Báo", MessageBoxButtons.OKCancel);

                if (d == DialogResult.OK)
                {
                    for (i = dataGridView14.Rows.Count - 2; i >= 0; i--)
                    {
                        check = dataGridView14.Rows[i].Cells["check_Editinput"].Value.ToString();
                        if (check == "1" || check == "True")
                        {
                            cmd.CommandText = "UPDATE [dbo].[KhoTP_NK] SET [LyDo] ='" + dataGridView14.Rows[i].Cells["LyDoMoi_Editinput"].Value.ToString() + "' WHERE [IDNumber]='" + dataGridView14.Rows[i].Cells["IDNumber_Editinput"].Value.ToString() + "'";
                            cmd.ExecuteNonQuery();
                            dataGridView14.Rows.RemoveAt(i);
                        }
                    }
                    MessageBox.Show("Dữ liệu được chỉnh sửa thành công");
                    bt_Edit_Editinput.Enabled = false;
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
            finally
            {
                Conn.Close();
                cmd.Dispose();
            }
        }

        private void bt_Check_Editinput_Click(object sender, EventArgs e)
        {
            try
            {

                for (i = dataGridView14.Rows.Count - 2; i >= 0; i--)
                {
                    check = dataGridView14.Rows[i].Cells["check_Editinput"].Value.ToString();
                    if (check == "0" || check == "False")
                    {

                        dataGridView14.Rows.RemoveAt(i);
                    }
                }
                bt_Edit_Editinput.Enabled = true;

            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }
        #endregion

        private void chk_selectall_CheckedChanged(object sender, EventArgs e)
        {
            if (chk_selectall.Checked == true)
            {
                if (dataGridView13.Rows.Count > 1)
                {
                    for (i = dataGridView13.Rows.Count - 2; i >= 0; i--)
                    {
                        dataGridView13.Rows[i].Cells["chk_pallets"].Value = true;
                    }
                }
            }
            else
            {
                if (dataGridView13.Rows.Count > 1)
                {
                    for (i = dataGridView13.Rows.Count - 2; i >= 0; i--)
                    {
                        dataGridView13.Rows[i].Cells["chk_pallets"].Value = false;
                    }
                }
            }
        }
        private void get_columns_gridoutput()
        {
            for (i = 0; i < dataGridView3.Columns.Count; i++)
            {
                string_temp = dataGridView3.Columns[i].Name.ToString();
                cb_Columns_Select.Items.Add(string_temp);
            }
        }

        private void cb_Columns_Select_SelectedIndexChanged(object sender, EventArgs e)
        {
            for (i = 0; i < dataGridView3.Columns.Count; i++)
            {
                if (cb_Columns_Select.Text == dataGridView3.Columns[i].Name.ToString())
                {
                    if (dataGridView3.Columns[i].Visible == true)
                        dataGridView3.Columns[i].Visible = false;
                    else
                        dataGridView3.Columns[i].Visible = true;
                }
            }
        }

       

       

        
    }
}
